I have this dataframe:
dates = pd.date_range(start='2016-01-01', periods=20, freq='d')
df = pd.DataFrame({'A': [1] * 20 + [2] * 12 + [3] * 8,
'B': np.concatenate((dates, dates)),
'C': np.arange(40)})
I sorted the data frame by Date:
df.sort_values('B',inplace=True)
I am looking to do a forward rolling sum on date. However, I can only do backward rolling sum using:
df.groupby('A').rolling(7, on='B',min_periods=0).C.sum()
A B
1 2016-01-01 0.0
2016-01-02 1.0
2016-01-03 3.0
2016-01-04 6.0
2016-01-05 10.0
2016-01-06 15.0
I want to do forward rolling sum.
I believe need change ordering by iloc[::-1]
:
df1 = (df.iloc[::-1]
.groupby('A', sort=False)
.rolling(7, on='B',min_periods=0).C
.sum()
.iloc[::-1])