Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: np.sum with negative axis

Tags:

numpy

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.

like image 899
Rainning Avatar asked Apr 28 '18 18:04

Rainning


1 Answers

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.

like image 94
wim Avatar answered Jan 03 '23 05:01

wim