Sum slices of consecutive values in a NumPy array Sum slices of consecutive values in a NumPy array numpy numpy

Sum slices of consecutive values in a NumPy array


One way is to use the add ufunc with its reduceat method:

>>> np.add.reduceat(a, [0,5])array([15, 40])

This sums the slices a[0:5] and a[5:] and returns a new array.

If you want a Python list, you could call tolist() on the returned array.

You can use any list of indexes with the method (and they do not have to evenly spaced). For example, if you want slices of 5 each time on an array of length 100:

>>> b = np.arange(100)>>> np.add.reduceat(b, range(0, 100, 5))array([ 10,  35,  60,  85, 110, 135, 160, 185, 210, 235, 260, 285, 310,   335, 360, 385, 410, 435, 460, 485])


Here's (yet) another solution:

In [3]: a.reshape((2,5)).sum(axis=1)Out[3]: array([15, 40])

Reshape the one-dimensional array to two rows of 5 columns and sum over the columns:

In [4]: a.reshape((2,5))Out[4]: array([[ 1,  2,  3,  4,  5],       [ 6,  7,  8,  9, 10]])

The sum along each row (summing the column entries) is specified with axis=1. The reshape happens without copying data (and without modifying the original a) so it is efficient and fast.


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