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:
array = [4,2,7,1]
ranks = [2,1,3,0]
Here’s the best method I’ve come up with:
array = numpy.array([4,2,7,1])
temp = array.argsort()
ranks = numpy.arange(len(array))[temp.argsort()]
Are there any better/faster methods that avoid sorting the array twice?
Use advanced indexing on the left-hand side in the last step:
This avoids sorting twice by inverting the permutation in the last step.