Description
The "obvious" way to get the rank of elements in a NumPy array is to use array.argsort().argsort()
:
https://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy
This is obviously slightly inefficient, due to sorting the array twice. In contrast, the optimal solution simply inverts the order of the array elements for the second argsort()
, which can be done in a single pass using indexing assignment:
array = numpy.array([4,2,7,1])
temp = array.argsort()
ranks = numpy.empty(len(array), int)
ranks[temp] = numpy.arange(len(array))
I'd like to propose adding an invert_permutation()
or inverse_permutation()
helper function to take care of this logic, which could be modeled off this helper function in xarray:
https://github.com/pydata/xarray/blob/2949558b75a65404a500a237ec54834fd6946d07/xarray/core/nputils.py#L38-L55
As precedent, note that TensorFlow has such a function, too: https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/invert_permutation