python - Numpy, grouping every N continuous element? -
i extract groups of every n continuous elements array. numpy array this:
a = numpy.array([1,2,3,4,5,6,7,8])
i wish have (n=5):
array([[1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7], [4,5,6,7,8]])
so can run further functions such average , sum. how produce such array?
you use rolling_window
blog
def rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) in [37]: = np.array([1,2,3,4,5,6,7,8]) in [38]: rolling_window(a, 5) out[38]: array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]])
i liked @divkar's solution. however, larger arrays , windows, may want use rolling_window
?
in [55]: = np.arange(1000) in [56]: %timeit rolling_window(a, 5) 100000 loops, best of 3: 9.02 µs per loop in [57]: %timeit broadcast_f(a, 5) 10000 loops, best of 3: 87.7 µs per loop in [58]: %timeit rolling_window(a, 100) 100000 loops, best of 3: 8.93 µs per loop in [59]: %timeit broadcast_f(a, 100) 1000 loops, best of 3: 1.04 ms per loop
Comments
Post a Comment