Sum of parts 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 summarize the first two values โ€‹โ€‹of the first line: 1+2 = 3 , then the following two values: 3+4 = 7 , and then 5+6 = 11 , etc. for each row. My desired result:

 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 overly complex, is there a better way? Perhaps built-in?

+6
source share
3 answers

When I need to do such things, I prefer to convert a 2D array to a 3D array, and then reset the extra dimension using np.sum . Generalizing it to n-dimensional arrays, you can do something like this:

 def sum_chunk(x, chunk_size, axis=-1): shape = x.shape if axis < 0: axis += x.ndim shape = shape[:axis] + (-1, chunk_size) + shape[axis+1:] x = x.reshape(shape) return x.sum(axis=axis+1) >>> a = np.arange(24).reshape(4, 6) >>> a array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]]) >>> sum_chunk(a, 2) array([[ 1, 5, 9], [13, 17, 21], [25, 29, 33], [37, 41, 45]]) >>> sum_chunk(a, 2, axis=0) array([[ 6, 8, 10, 12, 14, 16], [30, 32, 34, 36, 38, 40]]) 
+5
source

Just use slicing:

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

This takes an array formed by each column with even indices ( ::2 ), and adds it to the array formed by each column with odd indices ( 1::2 ).

+5
source

Here is one way:

 >>> a[:,::2] + a[:,1::2] array([[ 3, 7, 11], [15, 19, 23], [ 8, 13, 17]]) 
+1
source

Source: https://habr.com/ru/post/953015/


All Articles