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
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]])
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])
Eg the first element B[0,0] = 17
is the sum of the elements in
A[0, :, 0] = array([ 1, 4, 12])
np.sum()是垂直添加值,添加第一个列表中每个子列表的第一个元素:1 + 4 + 12 = 17,然后是第二个2 + 5 + 34 = 41等。
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.