49

I have an array of distances a = np.array([20.5 ,5.3 ,60.7 ,3.0 ], 'double') and I need the indices of the sorted array (for example [3, 1, 0, 2], for a.sort()). Is there a function in Numpy to do that?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • Please check out my solution in https://stackoverflow.com/questions/53442599/find-positions-of-elements-in-sorted-array/71993234#71993234 not specific to numpy, which also allows reverse (descending) )sort without need for reversing the array after it was sorted, and specification of a `key` function. – Max Apr 24 '22 at 23:51

2 Answers2

57

Yes, there's the x = numpy.argsort(a) function or x = numpy.ndarray.argsort(a) method. It does exactly what you're asking for. You can also call argsort as a method on an ndarray object like so: a.argsort().

Here's a link to the documentation: http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html#numpy.argsort

Phillip Cloud
  • 24,919
  • 11
  • 68
  • 88
14

Here's an example, for reference and convenience:

# create an array
a = np.array([5,2,3])

# np.sort - returns the array, sorted
np.sort(a)
>>> array([2, 3, 5])

# argsort - returns the original indexes of the sorted array
np.argsort(a)
>>> array([1, 2, 0])
Ollie Glass
  • 19,455
  • 21
  • 76
  • 107