gpt4 book ai didi

python - Groupby 求和并计算 python 中的多列

转载 作者:行者123 更新时间:2023-11-28 22:20:40 25 4
gpt4 key购买 nike

我有一个看起来像这样的 pandas 数据框

ID     country   month   revenue  profit   ebit
234 USA 201409 10 5 3
344 USA 201409 9 7 2
532 UK 201410 20 10 5
129 Canada 201411 15 10 5

我想按 ID、国家/地区、月份分组,计算每个月和国家/地区的 ID,然后对收入、利润、息税前利润求和。上述数据的输出为:

 country   month    revenue   profit  ebit   count
USA 201409 19 12 5 2
UK 201409 20 10 5 1
Canada 201411 15 10 5 1

我尝试了 pandas 的 groupby、sum 和 count 函数的不同变体,但我无法弄清楚如何一起应用 groupby sum 和 count 来给出如图所示的结果。请分享您可能有的任何想法。谢谢!

最佳答案

可以使用 pivot_table 以这种方式完成:

>>> df1=pd.pivot_table(df, index=['country','month'],values=['revenue','profit','ebit'],aggfunc=np.sum)
>>> df1
ebit profit revenue
country month
Canada 201411 5 10 15
UK 201410 5 10 20
USA 201409 5 12 19

>>> df2=pd.pivot_table(df, index=['country','month'], values='ID',aggfunc=len).rename('count')
>>> df2

country month
Canada 201411 1
UK 201410 1
USA 201409 2

>>> pd.concat([df1,df2],axis=1)

ebit profit revenue count
country month
Canada 201411 5 10 15 1
UK 201410 5 10 20 1
USA 201409 5 12 19 2

更新

可以使用 pivot_table 并提供一个函数字典以应用于 aggfunc 参数中的每一列:

pd.pivot_table(
df,
index=['country','month'],
aggfunc={'revenue': np.sum, 'profit': np.sum, 'ebit': np.sum, 'ID': len}
).rename(columns={'ID': 'count'})

count ebit profit revenue
country month
Canada 201411 1 5 10 15
UK 201410 1 5 10 20
USA 201409 2 5 12 19

关于python - Groupby 求和并计算 python 中的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48768650/

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