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

joshayers picture joshayers · Mar 12, 2011 · Viewed 88.4k times · Source

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?

Answer

k.rooijers picture k.rooijers · Jun 7, 2011

Use argsort twice, first to obtain the order of the array, then to obtain ranking:

array = numpy.array([4,2,7,1])
order = array.argsort()
ranks = order.argsort()

When dealing with 2D (or higher dimensional) arrays, be sure to pass an axis argument to argsort to order over the correct axis.