简体   繁体   中英

How to sum previous and next row values in pandas

After trying several hours i am still not able to perform the following task. I would like to sum to my center points the previous and next row value as shown in the image below

将上一个和下一个值加到中间点

Can you please provide me with an example how that can be done?

Thank you in advance for your time!

You can also use DF.rolling.sum() by providing center=True ( Since by default the labels are set to the right edge of the window ) and then take every third slice from it. Additionally, you can set the minimum number of observations, min_periods to be equal to 1 which basically says no output values will be set until at least min_periods non-null values are encountered.

df.A.rolling(window=3, min_periods=1, center=True).sum().iloc[::3].astype(int)

1      30
4     120
7     210
10    190
Name: A, dtype: int32

This will get it done

df = pd.DataFrame(dict(A=np.arange(10, 101, 10)), np.arange(1, 11))

pd.Series(np.convolve(df.A.values, [1, 1, 1])[1::3], df.index[0::3])

1      30
4     120
7     210
10    190
dtype: int64

​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM