gpt4 book ai didi

python - Pandas 将分组依据和行合并到列

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:21 24 4
gpt4 key购买 nike

我正在尝试转换此数据集:

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']
})

这里的答案有点接近,但枢轴对我来说不太适用。 How to do a transpose a dataframe group by key on pandas?

最佳答案

使用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

关于python - Pandas 将分组依据和行合并到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47991005/

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