6

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 2

6

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.])
Sign up to request clarification or add additional context in comments.

1 Comment

Go with the generic case, bincount is a bit faster anyway ;)
2

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.