2

I need to return the indexes that the elements of a list would have if the list was sorted in descending order.

For example given np.array([2,3,1,4,5]) I would like to receive array([3,2,4,1,0]).

Is there an easy way to obtain such an array?

George Francis
  • 462
  • 2
  • 7
  • 16
  • Does this answer your question? [Numpy argsort - what is it doing?](https://stackoverflow.com/questions/17901218/numpy-argsort-what-is-it-doing) – meshkati Feb 19 '21 at 09:39
  • No, but I found way to better describe what I want. I'd like to rank the elements of the array in descending order, such as what is done in https://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy-without-sorting-array-twice?noredirect=1&lq=1 but in descending rather than ascending order. – George Francis Feb 19 '21 at 09:50

2 Answers2

4

What you want is the ranks your elements would have in descending order.

a = np.array([2,3,1,4,5])
sorted_indices = np.argsort(-a)
ranks = np.empty_like(sorted_indices)
ranks[sorted_indices] = np.arange(len(a))

And result:

>>> ranks
array([3, 2, 4, 1, 0])
orlp
  • 112,504
  • 36
  • 218
  • 315
-1

You can use numpy's argsort (and it looks like you want the reverse order?)

a = np.array([2,3,1,4,5])
np.argsort(-a)
pregenRobot
  • 147
  • 1
  • 13