python / pandas滚动总和与时变窗口

时间:2018-03-07 20:26:23

标签: python pandas rolling-computation rolling-sum

我有一个数组

arr = [1,2,3, ..., N]

和窗口列表(长度为N)

windows = [2,2,1, ...]

是否可以在arr上进行滚动和计算,并在windows中存储时变窗口?

例如,在t = 3时,您有arr=[1,2,3]window=1,因此这表示返回1天的滚动总和,以便out[2] = 3

t=2,你有arr = [1,2]和window = 2,所以这表示2天的滚动总和,out[1]=3

2 个答案:

答案 0 :(得分:0)

我无法控制速度,但它会实现你所需要的

df['New']=np.clip(df.index-df.windows+1,a_min=0,a_max=None)
df
Out[626]: 
   val  windows  New
0    1        2    0
1    2        2    0
2    3        1    2
3    4        1    3
4    5        3    2

df.apply(lambda x : df.iloc[x['New']:x.name+1,0].sum(),1)
Out[630]: 
0     1
1     3
2     3
3     4
4    12
dtype: int64

答案 1 :(得分:0)

这可能就是你所追求的:

arr = [1,2,3]

windows = [2,2,1]

out = [0,0,0]

for t, i in enumerate(windows):
    newarr = arr[:t+1]
    out[t] = sum(newarr[:-(i+1):-1])

    print('t = ' + str(t+1))
    print('arr = ' + str(newarr))
    print('out[' + str(t) + '] = ' + str(out[t]))
    print('\n')

给出:

t = 1
arr = [1]
out[0] = 1


t = 2
arr = [1, 2]
out[1] = 3


t = 3
arr = [1, 2, 3]
out[2] = 3