Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum parts of numpy.array

Let's say I have the following array:

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

I want to sum the first two values of the first row: 1+2 = 3, then next two values: 3+4 = 7, and then 5+6 = 11, and so on for every row. My desired output is this:

array([[ 3,  7, 11],
       [15, 19, 23],
       [ 8, 13, 17]])

I have the following solution:

def sum_chunks(x, chunk_size):
    rows, cols = x.shape
    x = x.reshape(x.size / chunk_size, chunk_size)
    return x.sum(axis=1).reshape(rows, cols/chunk_size)

But it feels unnecessarily complicated, is there a better way? Perhaps a built-in?

like image 611
Akavall Avatar asked Sep 03 '13 00:09

Akavall


People also ask

How do you sum an array of elements in Python?

Method 2: Using the built-in function sum(). Python provides an inbuilt function sum() which sums up the numbers in the list. iterable: iterable can be anything list, tuples or dictionaries, but most importantly it should be numbered.

How do I sum across columns in NumPy?

Method 2: Using the sum() function in NumPy, numpy. sum(arr, axis, dtype, out) function returns the sum of array elements over the specified axis. To compute the sum of all columns the axis argument should be 0 in sum() function.

How do I sum two NumPy arrays?

To add the two arrays together, we will use the numpy. add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length. If the lengths of the two arrays are​ not the same, then broadcast the size of the shorter array by adding zero's at extra indexes.


1 Answers

Just use slicing:

a[:,::2] + a[:,1::2]

This takes the array formed by every even-indexed column (::2), and adds it to the array formed by every odd-indexed column (1::2).

like image 124
nneonneo Avatar answered Sep 23 '22 14:09

nneonneo