Numpy array return order

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

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

I would like to return an array:

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

Thus, the values ​​in the returned array indicate the increasing order of the array (i.e., the value in the returned array indicates which is the largest). Using argsort, I can only indicate how the values ​​should be reordered:

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

Let me know if this is unclear.

+4
source share
2 answers

Maybe the best way, but I always did 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]) 
+4
source

Assuming [2,3,0,1] is a typo for [2,3,1,0], you can 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]) 
+1
source

Source: https://habr.com/ru/post/1401470/


All Articles