Search code examples
pythonpandasrolling-average

pandas rolling window mean in the future


I would like to use the pandas.DataFrame.rolling method on a data frame with datetime to aggregate future values. It looks it can be done only in the past, is it correct?


Solution

  • 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