I have a data frame like this,
df
col1 col2
A 1
B 3
C 2
D 5
E 6
F 8
G 10
I want to add previous and next n values of a particular value of col2 and store it into a new column,
So, If n=2, then the data frame should look like,
col1 col2 col3
A 1 6 (only below 2 values are there no upper values, so adding 3 numbers)
B 3 11 (adding one prev, current and next two)
C 2 17(adding all 4 values)
D 5 24(same as above)
E 6 31(same as above)
F 8 29(adding two prev and next one as only one is present)
G 10 24(adding with only prev two values)
When previous or next 2 values are not found adding whatever values are available. I can do it using a for loop, but the execution time will be huge, looking for some pandas shortcuts do do it most efficiently.
5, 11, 17, 24....
– Joe Ferndz