Pandas:每个子组按月汇总

Pandas: Aggregate by month for every subgroup

我有以下pandastable

                          TUFNWGTP  TELFS  t070101  t070102  t070103  t070104  \
TUDIARYDATE status                                                              
2003-01-03  emp     8155462.672158      2        0        0        0        0   
2003-01-04  emp     1735322.527819      1        0        0        0        0   
            emp     3830527.482672      2       60        0        0        0   
2003-01-02  unemp   6622022.995205      4        0        0        0        0   
2003-01-09  emp     3068387.344956      1        0        0        0        0

我想将每日数据汇总为每月数据,每个子组

也就是说,如果没有status子索引,我会做

df.resample('M', how='sum')

如何对每个子组进行月度汇总?

我认为您需要一个 DatetimeIndex(而不是 MultiIndex):

In [11]: df1 = df.reset_index('status')

In [12]: df1
Out[12]:
            status        TUFNWGTP  TELFS  t070101  t070102  t070103  t070104
TUDIARYDATE
2003-01-03     emp  8155462.672158      2        0        0        0        0
2003-01-04     emp  1735322.527819      1        0        0        0        0
2003-01-04     emp  3830527.482672      2       60        0        0        0
2003-01-02   unemp  6622022.995205      4        0        0        0        0
2003-01-09     emp  3068387.344956      1        0        0        0        0

然后使用每月 TimeGrouper 状态列进行分组:

In [13]: df1.groupby([pd.TimeGrouper('M'), 'status']).sum()
Out[13]:
                           TUFNWGTP  TELFS  t070101  t070102  t070103  t070104
TUDIARYDATE status
2003-01-31  emp     16789700.027605      6       60        0        0        0
            unemp    6622022.995205      4        0        0        0        0