Consider the code below which gives the wanted output:
import numpy as np
import pandas as pd
sumvalues = 2
touchdown = 3
arr = np.array([1, 2, 3, 4, 5, 6, 7])
series = pd.Series(arr)
shifted = pd.Series(np.append(series, np.zeros(touchdown)))
rolled = shifted.rolling(window=sumvalues, min_periods=1).sum().fillna(0).astype(float)[touchdown:]
print(rolled.values)
As you can see, i want to shift my values by "touchdown" spots backwards and then compute for every entry the sum of the "sumvalues" preceding entries.
The issue with the code above is that it is slow, e.g we are creating a whole series object just to perform the rolling. Is there any smart(fast) way of achieving the same operations as above?
Tried to play around with the numpy roll function but it is a bit different, also tried the shift in pandas but seems inefficient.
You can use a
sliding_window_viewwithpad:Which you can further optimize to:
Output:
Output with
sumvalues = 5 ; touchdown = 0:Output with
sumvalues = 3 ; touchdown = 1: