Numpy: Find Index In Sorted Array (in An Efficient Way)
I would like to sort a numpy array and find out where each element went. numpy.argsort will tell me for each index in the sorted array, which index in the unsorted array goes there
Solution 1:
You can just use argsort
twice on the list.
At first the fact that this works seems a bit confusing, but if you think about it for a while it starts to make sense.
a = np.array([1, 4, 2, 3])
argSorted = np.argsort(a) # [0, 2, 3, 1]invArgSorted = np.argsort(argSorted) # [0, 3, 1, 2]
Solution 2:
You just need to invert the permutation that sorts the array. As shown in the linked question, you can do that like this:
import numpy as np
defsorted_position(array):
a = np.argsort(array)
a[a.copy()] = np.arange(len(a))
return a
print(sorted_position([0.1, 0.2, 0.0, 0.5, 0.8, 0.4, 0.7, 0.3, 0.9, 0.6]))
# [1 2 0 5 8 4 7 3 9 6]
Post a Comment for "Numpy: Find Index In Sorted Array (in An Efficient Way)"