user1403546
user1403546

Reputation: 1749

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?

Upvotes: 6

Views: 6870

Answers (2)

Antalagor
Antalagor

Reputation: 438

series.sort_index(ascending=False).rolling("2D").mean().sort_index()

you can reorder the series. the rolling window edges care about series order not about time order.

Upvotes: 1

Scott Boston
Scott Boston

Reputation: 153460

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

Upvotes: 5

Related Questions