Sachin Sharma
Sachin Sharma

Reputation: 89

What does the parameter -1 means in the sum method of the NumPy?

Consider the following code:

X = rand.rand(10, 2)
differences = X[:, np.newaxis, :] - X[np.newaxis, :, :]
differences = X[:, np.newaxis, :] - X[np.newaxis, :, :]
sq_differences = differences ** 2
dist_sq = sq_differences.sum(-1)

In this code, we're calculating the squared distance between the points in the cartesian plane (points are stored in the array X). Please explain the last step in this code, especially that -1 parameter in the sum method.

Upvotes: 0

Views: 126

Answers (1)

Jack Walton
Jack Walton

Reputation: 181

When Numpy.sum() is used to sum a multi dimenstional array it allows you to specify a dimension. For example dimension = 0 works along the column while dimemen =1 works along the row.

This is explained better here Numpy.sum

Now why -1 is used took a little more digging but is a very simple and sensible answer when you find it.

When you pass dimensions as -1 it means to pick the last dimension in the array. Such that in a 2D array this would be column

Upvotes: 1

Related Questions