6

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

4 Answers 4

7

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]])
Sign up to request clarification or add additional context in comments.

Comments

0

Let's call the inout array A and the output array B = np.sum(A, axis=1). It has elements B[i, j] which are calculated as

B[i, j] = np.sum(A[i, :, j])

E.g. the first element B[0,0] = 17 is the sum of the elements in

A[0, :, 0] = array([ 1,  4, 12])

Comments

0

np.sum() is adding the values vertically, the first element of each sub-list in the first list is added: 1+4+12 = 17, then the second 2+5+34=41 etc.

Comments

0

The array has shape (2,3,3); axis 1 is the middle one, of size 3. Eliminate that by sum and you are left with (2,3), the shape of your result.

Interpreting 3d is a little tricky. I tend to think of this array as having 2 planes, each plane has 3 rows, and 3 columns. The sum on axis 1 is over the rows of each plane.

1 + 4 + 12 == 17

In effect you are reducing each 2d plane to a 1d row.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.