问题
I would like to use the pandas rolling function
https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.rolling.html
on a pandas dataframe with datetime to aggregate future values. It looks it can be done only in the past, is this exact?
Thanks!
回答1:
IIUC, you can use shift to move you calculation back in time.
df = pd.DataFrame({'Data':np.arange(0,11,1)},index=pd.date_range('2018-07-23',periods=11))
df['rolling'] = df.rolling('2D').mean().shift(-1)
print(df)
Output:
Data rolling
2018-07-23 0 0.5
2018-07-24 1 1.5
2018-07-25 2 2.5
2018-07-26 3 3.5
2018-07-27 4 4.5
2018-07-28 5 5.5
2018-07-29 6 6.5
2018-07-30 7 7.5
2018-07-31 8 8.5
2018-08-01 9 9.5
2018-08-02 10 NaN
来源:https://stackoverflow.com/questions/51487017/pandas-rolling-window-mean-in-the-future