我想了解这个 ndarray.sum(axis=) 是如何工作的。我知道 axis=0 用于列,axis=1 用于行。 但在 3 维(3 轴)的情况下,很难解释以下结果。
arr = np.arange(0,30).reshape(2,3,5)
arr
Out[1]:
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]],
[[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]]])
arr.sum(axis=0)
Out[2]:
array([[15, 17, 19, 21, 23],
[25, 27, 29, 31, 33],
[35, 37, 39, 41, 43]])
arr.sum(axis=1)
Out[8]:
array([[15, 18, 21, 24, 27],
[60, 63, 66, 69, 72]])
arr.sum(axis=2)
Out[3]:
array([[ 10, 35, 60],
[ 85, 110, 135]])
在此示例中,3 轴数组 的形状为 (2,3,5),有 3 行和 5 列。但是,如果我从整体上看这个数组,似乎只有两行(都有 3 个数组元素)。
任何人都可以解释这个总和如何在 3 个或更多轴(维度)的数组上计算。
最佳答案
如果你想保留尺寸你可以指定keepdims
:
>>> arr = np.arange(0,30).reshape(2,3,5)
>>> arr.sum(axis=0, keepdims=True)
array([[[15, 17, 19, 21, 23],
[25, 27, 29, 31, 33],
[35, 37, 39, 41, 43]]])
否则,您求和的轴将从形状中移除。跟踪这一点的一种简单方法是使用 numpy.ndarray.shape
属性:
>>> arr.shape
(2, 3, 5)
>>> arr.sum(axis=0).shape
(3, 5) # the first entry (index = axis = 0) dimension was removed
>>> arr.sum(axis=1).shape
(2, 5) # the second entry (index = axis = 1) was removed
如果需要,您还可以沿多个轴求和(按指定轴的量减少维度):
>>> arr.sum(axis=(0, 1))
array([75, 81, 87, 93, 99])
>>> arr.sum(axis=(0, 1)).shape
(5, ) # first and second entry is removed
关于python - 在 numpy 数组中沿轴求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41733479/