Skip to content
Advertisement

Rank items in an array using Python/NumPy, without sorting array twice

I have an array of numbers and I’d like to create another array that represents the rank of each item in the first array. I’m using Python and NumPy.

For example:

JavaScript

Here’s the best method I’ve come up with:

JavaScript

Are there any better/faster methods that avoid sorting the array twice?

Advertisement

Answer

Use advanced indexing on the left-hand side in the last step:

JavaScript

This avoids sorting twice by inverting the permutation in the last step.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement