you can use pd.PeriodIndex(…, freq=’Q’) in conjunction with groupby(…, axis=1):
In [63]: df
Out[63]:
1996-04 1996-05 2000-07 2000-08 2010-10 2010-11 2010-12
0 1 2 3 4 1 1 1
1 25 19 37 40 1 2 3
2 10 20 30 40 4 4 5
In [64]: df.groupby(pd.PeriodIndex(df.columns, freq='Q'), axis=1).mean()
Out[64]:
1996Q2 2000Q3 2010Q4
0 1.5 3.5 1.000000
1 22.0 38.5 2.000000
2 15.0 35.0 4.333333
UPDATE: to get columns in a resulting DF as strings intead of period
dtype:
In [66]: res = (df.groupby(pd.PeriodIndex(df.columns, freq='Q'), axis=1)
.mean()
.rename(columns=lambda c: str(c).lower()))
In [67]: res
Out[67]:
1996q2 2000q3 2010q4
0 1.5 3.5 1.000000
1 22.0 38.5 2.000000
2 15.0 35.0 4.333333
In [68]: res.columns.dtype
Out[68]: dtype('O')
Just to add to @MaxU’s answer above, to convert the resulting PeriodIndex
columns back to str
and add spaces between year and quarter number (i.e. 1999 Q1
, not 1999Q1
), you can do this:
res = res.columns.to_series().astype(str)