numpy:负轴的np.sum

s̮̦*_*̥̳̼ 5 numpy

我想知道“ 如果轴为负数,则从最后一个轴算到第一个轴。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])
Run Code Online (Sandbox Code Playgroud)

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

wim*_*wim 7

首先看一看长度为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
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

因此,让我们看一下调用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])
Run Code Online (Sandbox Code Playgroud)

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

  • 有时您希望对最后一个轴进行索引,而不管输入的维数有多少。 (2认同)
  • 编写“t.sum(axis=-1)”比编写等效的“t.sum(axis=t.ndim-1)”更方便 (2认同)