Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing elements in a sliding window - NumPy

Tags:

python

numpy

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])
like image 505
marcelorodrigues Avatar asked Jul 21 '16 14:07

marcelorodrigues


1 Answers

Starting in Numpy 1.20, the sliding_window_view provides a way to slide/roll through windows of elements. Windows that you can then individually sum:

from numpy.lib.stride_tricks import sliding_window_view

# values = np.array([4, 2, 3, 8, -6, 10])
np.sum(sliding_window_view(values, window_shape = 3), axis = 1)
# array([9, 13, 5, 12])

where:

  • window_shape is the size of the sliding window
  • np.sum(array, axis = 1) sums sub-arrays

and the intermediate result of the sliding is:

sliding_window_view(np.array([4, 2, 3, 8, -6, 10]), window_shape = 3)
# array([[ 4,  2,  3],
#        [ 2,  3,  8],
#        [ 3,  8, -6],
#        [ 8, -6, 10]])
like image 84
Xavier Guihot Avatar answered Oct 19 '22 23:10

Xavier Guihot