您可以将pd.PeriodIndex(…,freq =’Q’)与groupby(…,axis =
1)结合使用 :
In [63]: dfOut[63]: 1996-04 1996-05 2000-07 2000-08 2010-10 2010-11 2010-120 1 2 3 4 1 1 11 25 19 37 40 1 2 32 10 20 30 40 4 4 5In [64]: df.groupby(pd.PeriodIndex(df.columns, freq='Q'), axis=1).mean()Out[64]: 1996Q2 2000Q3 2010Q40 1.5 3.5 1.0000001 22.0 38.5 2.0000002 15.0 35.0 4.333333
UPDATE :将结果DF中的列作为dtype的字符串插入
period:
In [66]: res = (df.groupby(pd.PeriodIndex(df.columns, freq='Q'), axis=1) .mean() .rename(columns=lambda c: str(c).lower()))In [67]: resOut[67]: 1996q2 2000q3 2010q40 1.5 3.5 1.0000001 22.0 38.5 2.0000002 15.0 35.0 4.333333In [68]: res.columns.dtypeOut[68]: dtype('O')


