gpt4 book ai didi

python - 如果某些值是整数范围,而其他值是纯整数,如何对 pandas DataFrame 进行分组?

转载 作者:行者123 更新时间:2023-12-01 07:44:31 24 4
gpt4 key购买 nike

我想按列 col_2 对 df 进行分组,该列主要包含整数,但某些单元格包含整数范围。在我的现实生活示例中,每个唯一整数代表组装零件的特定序列号。数据帧中的每一行代表一个零件,由 col_2 分配给组装零件。有些零件只能分配给具有给定不确定性(范围)的组装零件。
预期输出将是一个单个组对于每个引用的整数(组装零件S/N)。例如,条目 col_1 = c 应分配给 col_2 = 1 和 col_2 = 2 的两个组。


df = pd.DataFrame( {'col_1': ['a', 'b', 'c', 'd', 'e', 'f'],
'col_2': [1, 2, range(1,3), 3,range(2,5),5]})

col_1 col_2
0 a 1
1 b 2
2 c (1, 2)
3 d 3
4 e (2, 3, 4)
5 f 5

print(df.groupby(['col_2']).groups)

上面的代码出现错误:

TypeError: '<' not supported between instances of 'range' and 'int'

最佳答案

我认为这符合你的要求:

s = df.col_2.apply(pd.Series).set_index(df.col_1).stack().astype(int)
s.reset_index().groupby(0).col_1.apply(list)

第一步为您提供:

col_1   
a 0 1
b 0 2
c 0 1
1 2
d 0 3
e 0 2
1 3
2 4
f 0 5

最终结果是:

1       [a, c]
2 [b, c, e]
3 [d, e]
4 [e]
5 [f]

关于python - 如果某些值是整数范围,而其他值是纯整数,如何对 pandas DataFrame 进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56525236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com