gpt4 book ai didi

python - pandas:groupby 多列,连接一列同时添加另一列

转载 作者:太空宇宙 更新时间:2023-11-04 09:38:41 49 4
gpt4 key购买 nike

如果我有以下 df:

      amount   name   role    desc
0 1.0 a x f
1 2.0 a y g
2 3.0 b y h
3 4.0 b y j
4 5.0 c x k
5 6.0 c x l
6 6.0 c y p

我想按 namerole 列进行分组,将 amount 相加,然后对 进行串联desc, :

      amount   name   role    desc
0 1.0 a x f
1 2.0 a y g
2 7.0 b y h,j
4 11.0 c x k,l
6 6.0 c y p

解决这个问题的正确方法是什么?

附带问题:假设 df 是从 .csv 中读取的并且它有其他不相关的列,我如何进行此计算然后写入新的 .csv 以及其他列(与阅读的模式相同)?

最佳答案

可能不是确切的骗局,但有很多与 groupby agg 相关的问题

df.groupby(['name', 'role'], as_index=False)\
.agg({'amount':'sum', 'desc':lambda x: ','.join(x)})


name role amount desc
0 a x 1.0 f
1 a y 2.0 g
2 b y 7.0 h,j
3 c x 11.0 k,l
4 c y 6.0 p

编辑:如果数据框中还有其他列,您可以使用“first”或“last”聚合它们,或者如果它们的值相同,则将它们包括在分组中。

选项 1:

df.groupby(['name', 'role'], as_index=False).agg({'amount':'sum', 'desc':lambda x: ','.join(x), 'other1':'first', 'other2':'first'})

选项 2:

df.groupby(['name', 'role', 'other1', 'other2'], as_index=False).agg({'amount':'sum', 'desc':lambda x: ','.join(x)})

关于python - pandas:groupby 多列,连接一列同时添加另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52546386/

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