[英]sum numpy ndarray with 3d array along a given axis 1
I have an numpy ndarray with shape (2,3,3),for example: 我有一个形状(2,3,3)的numpy ndarray,例如:
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: 我在np.sum(在ndarray,轴= 1之上)迷路了,为什么答案是:
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).
二维阵列具有两个相应的轴:第一个在行(轴0)上垂直向下运行,第二个轴在列(轴1)上水平运行。
Let A be the array, then in your example when axis is 1, [i,:,k] are added. 设A为数组,然后在示例中,当轴为1时,添加[i,:,k]。 Likewise, for axis 0, [:,j,k] are added and when axis is 2, [i,j,:] are added.
同样,对于轴0,添加[:,j,k],当轴为2时,添加[i,j,:]。
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)
. 让我们调用inout数组
A
和输出数组B = np.sum(A, axis=1)
。 It has elements B[i, j]
which are calculated as 它具有元素
B[i, j]
,其被计算为
B[i, j] = np.sum(A[i, :, j])
Eg the first element B[0,0] = 17
is the sum of the elements in 例如,第一个元素
B[0,0] = 17
是元素的总和
A[0, :, 0] = array([ 1, 4, 12])
np.sum()是垂直添加值,添加第一个列表中每个子列表的第一个元素:1 + 4 + 12 = 17,然后是第二个2 + 5 + 34 = 41等。
The array has shape (2,3,3)
; 阵列有形状
(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. 轴1是中间的,大小为3.消除它的
sum
,你留下(2,3)
,你的结果的形状。
Interpreting 3d is a little tricky. 解释3d有点棘手。 I tend to think of this array as having 2 planes, each plane has 3 rows, and 3 columns.
我倾向于认为这个数组有2个平面,每个平面有3行,3列。 The sum on axis 1 is over the rows of each plane.
轴1上的总和超过每个平面的行。
1 + 4 + 12 == 17
In effect you are reducing each 2d plane to a 1d row. 实际上,您将每个2d平面减少到1d行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.