sum(-1) in np.array.sum(-1) mean?

Viewed 4703

I have just started working with numpy. while going through a sorting I came across np.ndarray.sum(-1).

the codes like this

rand_arr = np.random.rand(10, 2)
differences = rand_arr[:, np.newaxis, :] - rand_arr[np.newaxis, :, :]

so difference is a 3-D matrix of shape (10,10,2)

now they are using this command difference.sum(-1) # this will convert the 3-D matrix into 2-D matrix of shape (10,10)

so what this .sum(-1) means exactly?

1 Answers

According to numpy doc, It is sum along the axis=-1 which in python is last axis. In python indexing, -1 represents the last index. In your example, it is the sum of all elements along the 3rd axis, which results in a (10,10) shape. Here is a smaller example for easier representation:

arr = np.arange(2*3*4).reshape(2,3,4)
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

print(arr.sum(0)) #same as print(arr.sum(-3))
[[12 14 16 18]
 [20 22 24 26]
 [28 30 32 34]]

print(arr.sum(1)) #same as print(arr.sum(-2))
[[12 15 18 21]
 [48 51 54 57]]

print(arr.sum(2)) #same as print(arr.sum(-1))
[[ 6 22 38]
 [54 70 86]]
Related