Rank elements of numpy list in descending order

Viewed 672

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?

2 Answers

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])

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)
Related