简体   繁体   English

根据不同的列对数据框中的行求和

[英]sum rows in dataframe based on different columns

How can I merge rows in the given dataframe as shown below?如何合并给定数据框中的行,如下所示? For each account and currency, I have to sum the values, so that there's no division by sector.对于每个帐户和货币,我必须对这些值求和,以免按部门划分。

在此处输入图片说明

尝试

df.groupby(['acccount','currency'])['sum'].sum().reset_index()

我将对“帐户”、“货币”进行 groupby 操作,并在 sum 列上应用 sum 方法:

df.groupby(by=['account','currency'])['sum'].sum().reset_index()

您可以通过将accountcurrency设置为索引来避免 groupby,然后使用具有参数level pd.Series.sum取总和

df.set_index(['account','currency'])['sum'].sum(level=[0, 1]).reset_index()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM