所以,我正在学习大熊猫,我有这个问题。
假设我有一个这样的数据帧:
Object.entries(obj).slice(-1)
//[ ['prop4', {'prop': 'buzz'}] ]
我正在努力创造这个:
A B C
1 x NaN
2 y NaN
3 x NaN
4 x NaN
5 y NaN
基于B的相似之处。
我这样做了:
A B C
1 x [1,3,4]
2 y [2,5]
3 x [1,3,4]
4 x [1,3,4]
5 y [2,5]
我得到了这个。就像C列基于A列一样。
teste = df.groupby(['B'])
for name,group in teste:
df.loc[df['B'] == name[0],'C'] = group['A'].tolist()
任何人都可以向我解释为什么会发生这种情况,以及按照我想要的方式解决这个问题吗? 谢谢:))
答案 0 :(得分:6)
您可以先根据 B 列进行聚合,然后再与B
上的原始df联接:
df
# A B
#0 1 x
#1 2 y
#2 3 x
#3 4 x
#4 5 y
df.groupby('B').A.apply(list).rename('C').reset_index().merge(df)
# B C A
#0 x [1, 3, 4] 1
#1 x [1, 3, 4] 3
#2 x [1, 3, 4] 4
#3 y [2, 5] 2
#4 y [2, 5] 5
答案 1 :(得分:4)
您可以使用transform
创建列表。
In [324]: df['C'] = df.groupby('B')['A'].transform(lambda x: [x.values])
In [325]: df
Out[325]:
A B C
0 1 x [1, 3, 4]
1 2 y [2, 5]
2 3 x [1, 3, 4]
3 4 x [1, 3, 4]
4 5 y [2, 5]
答案 2 :(得分:1)
总结创意!
制作A
单值列表。然后使用sum
进行转换。
df.assign(
C=pd.Series(
df.A.values[:, None].tolist(), df.index
).groupby(df.B).transform('sum')
)
A B C
0 1 x [1, 3, 4]
1 2 y [2, 5]
2 3 x [1, 3, 4]
3 4 x [1, 3, 4]
4 5 y [2, 5]
答案 3 :(得分:0)
test = df.groupby('B')['A'].apply(list)