我想知道如何获取前两行本身和后两行的滚动总和。
import numpy as np
import pandas as pd
df = pd.DataFrame({'A': range(1,7)},index=range(1,7))
df['new'] = 0
for i in range(-2,2+1):
df['new'] += df.A.shift(i)
df
A new
1 1 NaN
2 2 NaN
3 3 15.0
4 4 20.0
5 5 NaN
6 6 NaN
我的上面的作品可以给出正确的答案,但是要计算均值,我必须除以5,并且其推广性不高。有内置方法或更好的替代方法吗?
答案 0 :(得分:3)
我们有rolling
df.A.rolling(5,center=True).mean()
Out[257]:
1 NaN
2 NaN
3 3.0
4 4.0
5 NaN
6 NaN
Name: A, dtype: float64