mike
mike

Reputation: 23821

Return order of NumPy array

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.

Upvotes: 8

Views: 7132

Answers (2)

Bi Rico
Bi Rico

Reputation: 25833

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

Upvotes: 13

DSM
DSM

Reputation: 353389

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

Upvotes: 1

Related Questions