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.
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.
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).
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.
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.
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])
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With