代码
s = pd.Series([0,1,2,3,4])
sr = s.rolling(3)
sr.apply(np.sum)
返回索引为[0,1,2,3,4]且值为[NaN,NaN,3,6,9]的系列。是否存在快速入侵,专门使用pandas滚动函数,以便它从跟随 3索引返回滚动总和,即使系列值为[3,6] ,9,NaN,NaN]?
答案 0 :(得分:3)
唯一的区别是转移-2:
w = 3
s.rolling(w).sum().shift(-w + 1)
0 3.0
1 6.0
2 9.0
3 NaN
4 NaN
dtype: float64
答案 1 :(得分:1)
添加iloc[::-1]
s = pd.Series([0,1,2,3,4])
sr = s.iloc[::-1].rolling(3)
sr.sum().iloc[::-1]
0 3.0
1 6.0
2 9.0
3 NaN
4 NaN
dtype: float64
答案 2 :(得分:1)
您需要numpy.roll()
s = pd.Series([0,1,2,3,4])
sr = s.rolling(3)
pd.Series(np.roll(sr.apply(np.sum),3))
输出:
0 3.0
1 6.0
2 9.0
3 NaN
4 NaN
dtype: float64