我想知道“如果轴为负,则从最后一个轴到第一个轴计数”是什么意思。意思是在 docs 中,我测试了这些:

>>> t
array([[1, 2],
       [3, 4]])
>>> np.sum(t, axis=1)
array([3, 7])
>>> np.sum(t, axis=0)
array([4, 6])
>>> np.sum(t, axis=-2)
array([4, 6])

仍然很困惑,我需要一些容易理解的解释。

最佳答案

首先看一下长度为 2 的列表上的列表索引:

>>> L = ['one', 'two']
>>> L[-1]  # last element
'two'
>>> L[-2]  # second-to-last element
'one'
>>> L[-3]  # out of bounds - only two elements in this list
# IndexError: list index out of range
axis 参数是类似的,除了它指定了 ndarray 的维度。如果使用非方形数组会更容易查看:
>>> t = np.arange(1,11).reshape(2,5)
>>> t
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])
>>> t.ndim  # two-dimensional array
2
>>> t.shape  # a tuple of length t.ndim
(2, 5)

那么让我们看看调用 sum 的各种方法:
>>> t.sum()  # all elements
55
>>> t.sum(axis=0)  # sum over 0th axis i.e. columns
array([ 7,  9, 11, 13, 15])
>>> t.sum(axis=1)  # sum over 1st axis i.e. rows
array([15, 40])
>>> t.sum(axis=-2)  # sum over -2th axis i.e. columns again (-2 % ndim == 0)
array([ 7,  9, 11, 13, 15])

尝试 t.sum(axis=-3) 将是一个错误,因为您在这个数组中只有 2 个维度。不过,您可以在 3d 阵列上使用它。

10-06 13:54
查看更多