0

I have an array

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

and a list of windows (of length N)

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

Is it possible to do a rolling sum computation on arr with the time varying windows stored in windows?

For example at t=3, you have arr=[1,2,3] and window=1 so this would indicate returning a 1 day rolling sum such that out[2] = 3

At t=2, you have arr = [1,2] and window=2 so this would indicate a 2 day rolling sum such that out[1]=3

cs95
  • 379,657
  • 97
  • 704
  • 746
Michael
  • 7,087
  • 21
  • 52
  • 81

2 Answers2

0

I can not grantee the speed , but it will achieve what you need

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
BENY
  • 317,841
  • 20
  • 164
  • 234
0

This might be what you are after:

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')

Gives:

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


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


t = 3
arr = [1, 2, 3]
out[2] = 3
rahlf23
  • 8,869
  • 4
  • 24
  • 54