gpt4 book ai didi

python - 求 pandas 中某些列的总和

转载 作者:行者123 更新时间:2023-11-30 22:28:14 29 4
gpt4 key购买 nike

我正在尝试使用 pandas 对某些列进行求和,同时保留其他列。例如:

member_no, data_1, data_2, data_3, dat_1, dat_2, other_1, other_2

1, 1, 3, 0, 0, 1, 1, 0

1, 1, 3, 0, 0, 1, 0, 1

2, 0, 1, 5, 1 ,0, 1, 0

2, 0, 1, 5, 1 ,0, 0, 1

我想要的结果是

member_no, data_1, data_2, data_3, dat_1, dat_2, other_1, other_2  

1, 1, 3, 0, 0, 1, 1, 1

2, 0, 1, 5, 1, 0, 1, 1

对于给定的成员 ID,所有包含“data”和“dat”的列都将具有相同的值,因此我只想保留该值。需要对具有“other”属性的列进行求和。

感谢您的帮助。

最佳答案

您正在寻找 member_no + max 上的 groupby

df = df.groupby('member_no', as_index=False).max()
print(df)
member_no data_1 data_2 data_3 dat_1 dat_2 other_1 other_2
0 1 1 3 0 0 1 1 1
1 2 0 1 5 1 0 1 1

关于python - 求 pandas 中某些列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46677440/

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