python - 求 pandas 中某些列的总和

标签 python pandas dataframe

我正在尝试使用 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/

相关文章:

python - 如何在 MultiIndex pandas DataFrame 中设置索引值?

python - 合并 Pandas 中的几个数据透视表

Python最快的n针到n haystacks字符串替换

python - 如何在python中实现负二项式损失函数以用于轻型GBM?

python - 如何将Python列表转换为pandas DataFrame :

python - 使用 pandas 应用

python - 如何获得 DataFrame 中列值的组合结果?

Python Tensorflow 训练-值错误 : Tensor must be from the same graph as Tensor

python - Flask 登录在请求之间不持久

Python Pandas 求和日期和描述