简体   繁体   English

如何对熊猫中的上一行和下一行值求和

[英]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. 您还可以通过提供center=True来使用DF.rolling.sum()由于默认情况下,标签设置为窗口的右边缘 ),然后从中获取每三个切片。 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. 另外,您可以将最小观察值min_periods设置为等于1,这基本上表示直到遇到至少min_periods非空值之前,才设置输出值。

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

​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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