Summing elements in a sliding window - NumPy
An answer to this question on Stack Overflow.
Question
There is a numpy way to make a sum each three elements in the interval? For example:
import numpy as np
mydata = np.array([4, 2, 3, 8, -6, 10])
I would like to get this result:
np.array([9, 13, 5, 12])
Answer
A solution without using external libraries might look like this:
from collections import deque
def sliding_window_sum(a, size):
out = []
the_sum = 0
q = deque()
for i in a:
if len(q)==size:
the_sum -= q[0]
q.popleft()
q.append(i)
the_sum += i
if len(q)==size:
out.append(the_sum)
return out
v = [0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1]
sliding_window_sum(v, 5)
Which gives the output:
[1, 2, 3, 3, 4, 4, 3, 2, 3, 2, 1, 1, 1, 0, 0, 1]
This matches the result of using numpy:
import numpy as np
np.convolve(v, np.ones(5, dtype=int),'valid').tolist()