Pandas 将 group by 和行组合成列 [英] pandas combine group by and rows to columns
本文介绍了Pandas 将 group by 和行组合成列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试转换此数据集:
I'm trying to transform this dataset:
A B C
1 x1 a
1 x1 a
1 x1 b
2 x2 b
2 x2 a
进入:
A B C1 C2 C3
1 x1 a a b
2 x2 b a null
df = pd.DataFrame({ 'A': [1, 1, 1, 2, 2],
'B': ['x1', 'x1', 'x1', 'x2', 'x2'],
'C': ['a', 'a', 'b', 'b', 'a']
})
这里的答案在某种程度上很接近,但支点对我来说不太适用.如何转置数据帧组按熊猫键?
The answer from here is somehow close but the pivot does not quite work for me. How to do a transpose a dataframe group by key on pandas?
推荐答案
Use groupby
+ apply
-
v = df.groupby(['A' ,'B']).C.apply(lambda x: x.tolist())
df = pd.DataFrame(v.tolist(), index=v.index)\
.rename(columns=lambda x: x + 1)\
.add_prefix('C')\
.reset_index()
df
A B C1 C2 C3
0 1 x1 a a b
1 2 x2 b a None
这篇关于Pandas 将 group by 和行组合成列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文