xlinsist xlinsist - 6 months ago 58
Python Question

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

Answer

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 axis is 1, [i,:,k] are 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]])