sum every N elements from numpy array

Viewed 50

For example, given an array

arr = np.array([1,2,3,2,3,7,2,3,4])

there are 9 elements.

I want to get sum every 3 elements:

[6, 12, 9]

Is there any numpy api I can use?

2 Answers

If your arr can be divided into groups of 3, i.e. has length 3*k, then:

arr.reshape(-1,3).sum(axis=-1)
# array([ 6, 12,  9])

In the general case, bincounts:

np.bincount(np.arange(len(arr))//3, arr)
# array([ 6., 12.,  9.])

If the length of arr is not a multiple of 3, consider using np.add.reduceat:

>>> arr = np.array([1,2,3,2,3,7,2,3,4,5])
>>> np.add.reduceat(arr, np.arange(0, arr.size, 3))
array([ 6, 12,  9,  5])
Related