0

In pandas, how can I write a rolling window that has preceding as well as following rows?

for example, a sql rolling window can be written as follows:

sum(id_0) over (partition by id_1 order by id_2 rows between 3 preceding and 1 following)

i am not sure how to write this in pandas.

toing
  • 366
  • 2
  • 13

1 Answers1

1

You can calculate the rolling sum for 4 preceding values then use the shift() method to apply those values to one row prior - for example:

rolling_ds = dataset.rolling(4, min_periods=1).sum().shift(-1)

A more robust discussion of this approach can be found here: Calculating Rolling forward averages with pandas

Adam Luchjenbroers
  • 4,686
  • 2
  • 27
  • 34