8

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.

4
  • 1
    Are you sure you want [2,3,0,1] and not [2,3,1,0]? Commented Mar 14, 2012 at 21:05
  • 2
    I do not understand how you arrive at array([2, 3, 0, 1]) from your description. Commented Mar 14, 2012 at 21:05
  • 1
    possible duplicate of Rank items in an array using Python/NumPy Commented Mar 14, 2012 at 21:07
  • 1
    Thank for checking into this, I found a good answer here: stackoverflow.com/questions/5284646/… Commented Mar 14, 2012 at 21:08

2 Answers 2

13

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])
Sign up to request clarification or add additional context in comments.

Comments

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.