Home > Software engineering >  sum every N elements from numpy array
sum every N elements from numpy array

Time:09-21

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?

CodePudding user response:

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.])
  • Related