Numpy: np.sum with negative axis

前端 未结 1 658
傲寒
傲寒 2021-01-12 10:25

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,          


        
相关标签:
1条回答
  • 2021-01-12 10:34

    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.

    0 讨论(0)
提交回复
热议问题