df = pd.DataFrame({'values':[2,6,1,5,8,9]})
我试图创建一个名为sum
的新rom,它是3个最新值的总和。所以它会返回[np.nan, np.nan, 9, 12, 14, 22]
答案 0 :(得分:3)
print (df.rolling(3).sum())
values
0 NaN
1 NaN
2 9.0
3 12.0
4 14.0
5 22.0
或者:
print (df['values'].rolling(3).sum())
0 NaN
1 NaN
2 9.0
3 12.0
4 14.0
5 22.0
Name: values, dtype: float64
df['sum'] = df['values'].rolling(3).sum()
print (df)
values sum
0 2 NaN
1 6 NaN
2 1 9.0
3 5 12.0
4 8 14.0
5 9 22.0
答案 1 :(得分:1)
关注性能,这是使用NumPy's 1D convolution
-
np.append([np.nan]*2,np.convolve(df['values'],np.ones((3,)),'valid'))