Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 450
mike Avatar asked Mar 14 '12 20:03

mike


People also ask

Can you sort NumPy array?

Sorting means putting elements in an ordered sequence. Ordered sequence is any sequence that has an order corresponding to elements, like numeric or alphabetical, ascending or descending. The NumPy ndarray object has a function called sort() , that will sort a specified array.

What is NumPy order C?

order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest).

What does NumPy arange return?

NumPy arange() is one of the array creation routines based on numerical ranges. It creates an instance of ndarray with evenly spaced values and returns the reference to it.

What does Argsort return?

Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.


2 Answers

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])
like image 86
Bi Rico Avatar answered Oct 19 '22 00:10

Bi Rico


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])
like image 45
DSM Avatar answered Oct 18 '22 22:10

DSM