Sum slices of consecutive values in a NumPy array

2020-02-12 07:09发布

问题:

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?

回答1:

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



回答2:

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


回答3:

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.



回答4:

You could use

import numpy as np

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

for i in range(0,a.shape[0],step):
    print(np.sum(a[i:i+step]))