Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum numpy ndarray with 3d array along a given axis 1

I have an numpy ndarray with shape (2,3,3),for example:

array([[[ 1,  2,  3],
    [ 4,  5,  6],
    [12, 34, 90]],

   [[ 4,  5,  6],
    [ 2,  5,  6],
    [ 7,  3,  4]]])

I am getting lost in np.sum(above ndarray ,axis=1), why that answer is:

array([[17, 41, 99],
   [13, 13, 16]])

Thanks

like image 438
vincent Avatar asked May 10 '16 14:05

vincent


People also ask

What is the 1 axis in NumPy?

Axis 1 is the direction along the columns In a multi-dimensional NumPy array, axis 1 is the second axis. When we're talking about 2-d and multi-dimensional arrays, axis 1 is the axis that runs horizontally across the columns.

Does += work with NumPy arrays?

Numpy arrays are mutable objects that have clearly defined in place operations. If a and b are arrays of the same shape, a += b adds the two arrays together, using a as an output buffer.

How does NumPy sum axis work?

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. Having said that, it can get a little more complicated. It's possible to also add up the rows or add up the columns of an array.


1 Answers

Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0), and the second running horizontally across columns (axis 1).

Let A be the array, then in your example when the axis is 1, [i,:,k] is added. Likewise, for axis 0, [:,j,k] are added and when axis is 2, [i,j,:] are added.

A = np.array([
   [[ 1,  2,  3],[ 4,  5,  6], [12, 34, 90]],
   [[ 4,  5,  6],[ 2,  5,  6], [ 7,  3,  4]]
])

np.sum(A,axis = 0)
    array([[ 5,  7,  9],
           [ 6, 10, 12],
           [19, 37, 94]])
np.sum(A,axis = 1)
    array([[17, 41, 99],
           [13, 13, 16]])
np.sum(A,axis = 2)
    array([[ 6, 15,136],
           [15, 13, 14]])
like image 191
modestfool Avatar answered Oct 04 '22 06:10

modestfool