7

I'm trying to return an array which has the rank of each value in an array. For example, given the array below:

import numpy as np
arr1 = np.array([4, 5, 3, 1])

I would want to return the array:

array([2, 3, 1, 0])

Such that the values in the returned array indicate the ascending order of the array (ie, the value in the returned array indicates which is largest). Using argsort, I can only tell how the values should be reordered:

arr1.argsort()
array([3, 2, 0, 1])

Let me know if this is unclear.

double-beep
  • 5,031
  • 17
  • 33
  • 41
mike
  • 22,931
  • 31
  • 77
  • 100
  • 1
    Are you sure you want [2,3,0,1] and not [2,3,1,0]? – DSM Mar 14 '12 at 21:05
  • 2
    I do not understand how you arrive at `array([2, 3, 0, 1])` from your description. – Mike Graham Mar 14 '12 at 21:05
  • 1
    possible duplicate of [Rank items in an array using Python/NumPy](http://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy) – mike Mar 14 '12 at 21:07
  • 1
    Thank for checking into this, I found a good answer here: http://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy – mike Mar 14 '12 at 21:08

2 Answers2

12

There might be a better way but I've allways done argsort().argsort():

>>> import numpy as np
>>> a = np.random.random(5)
>>> a
array([ 0.54254555,  0.4547267 ,  0.50008037,  0.20388227,  0.13725801])
>>> a.argsort().argsort()
array([4, 2, 3, 1, 0])
Bi Rico
  • 25,283
  • 3
  • 52
  • 75
1

Assuming that [2,3,0,1] is a typo for [2,3,1,0], you could use lexsort:

>>> import numpy as np
>>> arr1 = np.array([4,5,3,1])
>>> np.lexsort((np.arange(len(arr1)), arr1.argsort()))
array([2, 3, 1, 0])
DSM
  • 342,061
  • 65
  • 592
  • 494