Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do pandas rolling window in both forward and backward at the same time

I have a pd.DataFrame df with one column, say:

A = [1,2,3,4,5,6,7,8,2,4]
df = pd.DataFrame(A,columns = ['A'])

For each row, I want to take previous 2 values, current value and next 2 value (a window= 5) and get the sum and store it in new column. Desire output,

   A  A_sum
  1      6
  2     10
  3     15
  4     20
  5     25
  6     30
  7     28
  8     27
  2     21
  4     14

I have tried,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. df['A_sum'] = df['A'].rolling(2).sum()
  2. Tried with shift, but all doing either forward or backward, I’m looking for a combination of both.

>Solution :

Use rolling by 5, add parameter center=True and min_periods=1 to Series.rolling:

df['A_sum'] =  df['A'].rolling(5, center=True, min_periods=1).sum()
print (df)
   A  A_sum
0  1    6.0
1  2   10.0
2  3   15.0
3  4   20.0
4  5   25.0
5  6   30.0
6  7   28.0
7  8   27.0
8  2   21.0
9  4   14.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading