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
x
3
1
array = [4,2,7,1]
2
ranks = [2,1,3,0]
3
Here’s the best method I’ve come up with:
JavaScript
1
4
1
array = numpy.array([4,2,7,1])
2
temp = array.argsort()
3
ranks = numpy.arange(len(array))[temp.argsort()]
4
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
1
5
1
array = numpy.array([4,2,7,1])
2
temp = array.argsort()
3
ranks = numpy.empty_like(temp)
4
ranks[temp] = numpy.arange(len(array))
5
This avoids sorting twice by inverting the permutation in the last step.