如何按多级行对python数据框进行分组? [英] How to group a python data frame by multilevel rows?

查看:45
本文介绍了如何按多级行对python数据框进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下多级数据框:

Year   2016                    2017                 
Quarter  3   4                 1                 2      
Month  Sep   Oct   Nov   Dec   Jan  Feb    Mar   Apr   May   Jun
A      0.16  0.95  0.92  0.45  0.30  0.35  0.95  0.88  0.18  0.10
B      0.88  0.67  0.07  0.70  0.74  0.33  0.77  0.21  0.81  0.85
C      0.79  0.56  0.13  0.19  0.94  0.23  0.72  0.62  0.66  0.93

我想总结几个季度,所以最终结果如下:

I want to sum up over the quarters, so that the final result is as follows:

Year     2016        2017   
Quarter  3     4     1     2
A        0.16  2.32  1.60  1.16
B        0.88  1.44  1.85  1.86
C        0.79  0.89  1.89  2.21

我尝试了以下公式:

df= df.groupby('Quarter').transform('sum')

但我收到此错误:

KeyError: 'Quarter'

显然这是错误的处理方式.任何人都可以请一个解决方案或接近找到一个.

Clearly that's the wrong way to approach it. Could anyone please a solution or to approach finding one.

其他信息

df.index 命令的输出是:Index([u'A', u'B',u'C'],dtype='object', name=u'DF 名称')

谢谢!

推荐答案

Just using sum

Just using sum

df.sum(level=[0,1],axis=1)
Out[14]: 
year    2016        2017      
quater     3     4     1     2
A       0.16  2.32  1.60  1.16
B       0.88  1.44  1.84  1.87
C       0.79  0.88  1.89  2.21

这篇关于如何按多级行对python数据框进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆