如何在 pandas 的多个列上分组和汇总 [英] How to group by and aggregate on multiple columns in pandas
本文介绍了如何在 pandas 的多个列上分组和汇总的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在熊猫中有以下数据框
I have following dataframe in pandas
ID Balance ATM_drawings Value
1 100 50 345
1 150 33 233
2 100 100 333
2 100 100 234
我想要采用所需格式的数据
I want data in that desired format
ID Balance_mean Balance_sum ATM_Drawings_mean ATM_drawings_sum
1 75 250 41.5 83
2 200 100 200 100
我正在使用以下命令在熊猫中完成
I am using following command to do it in pandas
df1= df[['Balance','ATM_drawings']].groupby('ID', as_index = False).agg(['mean', 'sum']).reset_index()
但是,它没有给出我想要得到的.
But, it does not give what I intended to get.
推荐答案
您可以使用字典为每个系列指定聚合函数:
You can use a dictionary to specify aggregation functions for each series:
d = {'Balance': ['mean', 'sum'], 'ATM_drawings': ['mean', 'sum']}
res = df.groupby('ID').agg(d)
# flatten MultiIndex columns
res.columns = ['_'.join(col) for col in res.columns.values]
print(res)
Balance_mean Balance_sum ATM_drawings_mean ATM_drawings_sum
ID
1 125 250 41.5 83
2 100 200 100.0 200
或者您可以通过 dict.fromkeys
定义 d
:
d = dict.fromkeys(('Balance', 'ATM_drawings'), ['mean', 'sum'])
这篇关于如何在 pandas 的多个列上分组和汇总的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文