NumPy中的axis参数如何工作? [英] How does the axis parameter from NumPy work?
问题描述
有人可以确切解释NumPy中的axis
参数做什么吗?
Can someone explain exactly what the axis
parameter in NumPy does?
我非常困惑.
我正在尝试使用功能myArray.sum(axis=num)
起初,我以为如果数组本身是3维,则axis=0
将返回三个元素,由位于同一位置的所有嵌套项的总和组成.如果每个维度包含五个维度,则我期望axis=1
返回五个项目的结果,依此类推.
At first I thought if the array is itself 3 dimensions, axis=0
will return three elements, consisting of the sum of all nested items in that same position. If each dimension contained five dimensions, I expected axis=1
to return a result of five items, and so on.
但是事实并非如此,文档不能很好地帮助我(他们使用3x3x3数组,因此很难说出正在发生的事情)
However this is not the case, and the documentation does not do a good job helping me out (they use a 3x3x3 array so it's hard to tell what's happening)
这就是我所做的:
>>> e
array([[[1, 0],
[0, 0]],
[[1, 1],
[1, 0]],
[[1, 0],
[0, 1]]])
>>> e.sum(axis = 0)
array([[3, 1],
[1, 1]])
>>> e.sum(axis=1)
array([[1, 0],
[2, 1],
[1, 1]])
>>> e.sum(axis=2)
array([[1, 0],
[2, 1],
[1, 1]])
>>>
显然结果不直观.
推荐答案
很显然,
e.shape == (3, 2, 2)
轴上的总和是归约运算,因此指定的轴消失.因此,
Sum over an axis is a reduction operation so the specified axis disappears. Hence,
e.sum(axis=0).shape == (2, 2)
e.sum(axis=1).shape == (3, 2)
e.sum(axis=2).shape == (3, 2)
这篇关于NumPy中的axis参数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!