Numpy:带有负轴的 np.sum [英] Numpy: np.sum with negative axis
问题描述
我想知道如果轴为负数,则从最后一个轴到第一个轴计数."在 docs,我已经测试过这些:
<预><代码>>>>吨数组([[1, 2],[3, 4]])>>>np.sum(t,axis=1)数组([3, 7])>>>np.sum(t,axis=0)数组([4, 6])>>>np.sum(t,axis=-2)数组([4, 6])仍然困惑,我需要一些易于理解的解释.
首先看一下长度为 2 的列表上的列表索引:
<预><代码>>>>L = ['一','二']>>>L[-1] # 最后一个元素'二'>>>L[-2] # 倒数第二个元素'一'>>>L[-3] # 越界——这个列表中只有两个元素# IndexError: 列表索引超出范围axis
参数是类似的,除了它指定 ndarray 的维度.如果使用非方形数组会更容易看出:
那么让我们看看调用 sum 的各种方法:
<预><代码>>>>t.sum() # 所有元素55>>>t.sum(axis=0) # 在第 0 个轴上求和,即列数组([ 7, 9, 11, 13, 15])>>>t.sum(axis=1) # 对第一个轴即行求和数组([15, 40])>>>t.sum(axis=-2) # 对 -2th 轴求和,即再次列 (-2 % ndim == 0)数组([ 7, 9, 11, 13, 15])尝试 t.sum(axis=-3)
会出错,因为这个数组中只有 2 个维度.不过,您可以在 3d 阵列上使用它.
I wonder what does "If axis is negative it counts from the last to the first axis." mean in the docs, I've test these:
>>> 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])
Still confused, I need some easily understood explanation.
First look at list indexing on a length-2 list:
>>> 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
The axis
argument is analogous, except it's specifying the dimension of the ndarray. It will be easier to see if using a non-square array:
>>> 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)
So let's look at the various ways to call 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])
Trying t.sum(axis=-3)
will be an error, because you only have 2 dimensions in this array. You could use it on a 3d array, though.
这篇关于Numpy:带有负轴的 np.sum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!