Skip to content
Advertisement

Sum slices of consecutive values in a NumPy array

Let’s say I have a numpy array a containing 10 values. Just an example situation here, although I would like to repeat the same for an array with length 100.

a = np.array([1,2,3,4,5,6,7,8,9,10])

I would like to sum the first 5 values followed by the second 5 values and so on and store them in a new empty list say b.

So b would contain b = [15,40].

How do I go about doing it?

Advertisement

Answer

Try this list comprehension:

b = [sum(a[current: current+5]) for current in xrange(0, len(a), 5)]

It takes slices of 5 at a time from the list, sums them up and constructs a list. Also works for lists which aren’t a multiple of 5 in length.

(xrange should be range in python3+)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement