6

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?

Jaroslav Bezděk
  • 6,967
  • 6
  • 29
  • 46
user1403546
  • 1,680
  • 4
  • 22
  • 43

2 Answers2

4

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
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • 1
    The shift(-1) doesn't work well in case you have holes in your dates, which might sometimes be the case. – gvo Oct 02 '22 at 01:24
  • Fill your series with missing dates then shift. Maybe. @gvo – Scott Boston Oct 02 '22 at 14:52
  • 1
    Well, filling with what? For a min or a max, it's quite easy, for a sum as well, but for a mean... Not that much. And it's very related to the aggregation you which to do, which might or might not be not that clean. – gvo Oct 04 '22 at 17:31
  • @gvo Yes, understood. – Scott Boston Oct 04 '22 at 18:05
  • This does not work as intended! We want to have a roll over some defined time range after the series index times. But instead we receive for each time index, what happened a defined time range before the next index time! – Antalagor Mar 22 '23 at 11:11
  • @Antalagor It doesn't work as *you* intended? Please post a new question with sample data and expected output. I am sure the SO community can help you. – Scott Boston Mar 22 '23 at 11:29
1
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.

Antalagor
  • 428
  • 4
  • 10