Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 225
user3397243 Avatar asked Apr 01 '15 13:04

user3397243


People also ask

How do I sum a row wise in NumPy?

The numpy. sum() function is available in the NumPy package of Python. This function is used to compute the sum of all elements, the sum of each row, and the sum of each column of a given array. Essentially, this sum ups the elements of an array, takes the elements within a ndarray, and adds them together.

How do I slice a row in NumPy array?

To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .

Can you sum a NumPy array?

NumPy sum adds up the values of a NumPy array Essentially, the NumPy sum function sums up the elements of an array. It just takes the elements within a NumPy array (an ndarray object) and adds them together.


1 Answers

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.

like image 108
xnx Avatar answered Oct 04 '22 18:10

xnx