Skip to content Skip to sidebar Skip to footer

Fast Rolling-sum For List Of Data Vectors (2d Matrix)

I am looking for a fast way to compute a rolling-sum, possibly using Numpy. Here is my first approach: def func1(M, w): Rtn = np.zeros((M.shape[0], M.shape[1]-w+1)) for

Solution 1:

Adapted from @Jaime's answer here: https://stackoverflow.com/a/14314054/553404

import numpy as np

def rolling_sum(a, n=4) :
    ret = np.cumsum(a, axis=1, dtype=float)
    ret[:, n:] = ret[:, n:] - ret[:, :-n]
    return ret[:, n - 1:]

M = np.array([[0.,  0.,  0.,  0.,  0.,  1.,  1.,  0.,  1.,  1.,  1.,  0.,  0.],
              [0.,  0.,  1.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.],
              [1.,  1.,  0.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.]])

print(rolling_sum(M)) 

Output

[[ 0.  0.  1.  2.  2.  3.  3.  3.  3.  2.]
 [ 1.  2.  2.  1.  1.  0.  0.  0.  1.  2.]
 [ 3.  2.  1.  1.  1.  1.  1.  1.  0.  0.]]

Timings

In [7]: %timeit rolling_sum(M, 4)
100000 loops, best of 3: 7.89 µs per loop

In [8]: %timeit func1(M, 4)
10000 loops, best of 3: 70.4 µs per loop

In [9]: %timeit func2(M, 4)
10000 loops, best of 3: 54.1 µs per loop

Post a Comment for "Fast Rolling-sum For List Of Data Vectors (2d Matrix)"