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])
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 windownp.sum(array, axis = 1)
sums sub-arraysand 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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With