Here the attempt is not super clean, but it can work.
Dummy data:
df = pd.DataFrame(data={'a': 1.}, index=pd.date_range(start='2001-1-1', periods=1000))
First, define a function to reduce the date n number of months. This needs to be cleared, but works for n <= 12.
from datetime import datetime def decrease_month(date, n): assert(n <= 12) new_month = date.month - n year_offset = 0 if new_month <= 0: year_offset = -1 new_month = 12 + new_month return datetime(date.year + year_offset, new_month, 1)
Then add 5 new columns for the 5 rolling periods that will cross each date.
for n in range(rolling_period): df['m_' + str(n)] = df.index.map(lambda x: decrease_month(x, n))
Then - use the melt function to convert data from wide-angle to long, so each rolling period will have one record.
df_m = pd.melt(df, id_vars='a')
You should be able to group the newly created column, and each date will represent a valid period of 5 months.
In [222]: df_m.groupby('value').sum() Out[222]: a value 2000-09-01 31 2000-10-01 59 2000-11-01 90 2000-12-01 120 2001-01-01 151 2001-02-01 150 2001-03-01 153 2001-04-01 153 2001-05-01 153 2001-06-01 153 2001-07-01 153 ...
source share