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

标签 python python-3.x python-2.7 pandas pandas-groupby

我有一个看起来像这样的 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/

相关文章:

python - 使用适配器时如何在 TraitsUI TreeView 中启用右键单击菜单?

python - 为什么这个解决方案的复杂度为 O(nlogn)?

python - 凯撒密码 python 加密

python - pip 安装 getch : clang error

python - 从 CSV 中提取信息

python - torch.rot90 的旋转方向

Python树遍历和排序列表中的项目组排序

python-3.x - 当模型包含张量操作时,Pytorch DataParallel 不起作用

python-3.x - 带有pandas和numpy的Pyinstaller,exe在运行时抛出错误

python - 如何使用 matplotlibs 颜色图 alpha 值使三色图淡入透明?