Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sum every N elements from numpy array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[6, 12, 9]

Is there any numpy api I can use?

>Solution :

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.])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading