Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the sum of every 5 elements in a python array

I have a python array in which I want to calculate the sum of every 5 elements. In my case I have the array c with ten elements. (In reality it has a lot more elements.)

c = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0]

So finally I would like to have a new array (c_new) which should show the sum of the first 5 elements, and the second 5 elements

So the result should be that one

1+0+0+0+0 = 1
2+0+0+0+0 = 2

c_new = [1, 2]

Thank you for your help Markus

like image 816
Markus Avatar asked Feb 24 '17 16:02

Markus


2 Answers

You can use np.add.reduceat by passing indices where you want to split and sum:

import numpy as np
c = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0]
np.add.reduceat(c, np.arange(0, len(c), 5))
# array([1, 2])
like image 122
Psidom Avatar answered Sep 19 '22 14:09

Psidom


Heres one way of doing it -

c = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0]
print [sum(c[i:i+5]) for i in range(0, len(c), 5)]

Result -

[1, 2]
like image 40
hashcode55 Avatar answered Sep 22 '22 14:09

hashcode55