I have a numpy array of floats/ints and want to map its elements into their ranks.
If an array doesn\'t have duplicates the problem can be solved by the following co
Here is a function that can return the output you desire (in the first case)
def argsortdup(a1):
sorted = sort(a1)
ranked = []
for item in a1:
ranked.append(sorted.searchsorted(item))
return array(ranked)
Basically you sort it and then you search for the index the item is at. Assuming duplicates the first instance index should be returned. I tested it with your a2 example and doing something like
a3 = argsortdup(a2)
Yields
array([0, 1, 4, 5, 6, 1, 7, 8, 8, 1])
"Test with a2":
>>> a2
array([ 0.1, 1.1, 2.1, 3.1, 4.1, 1.1, 6.1, 7.1, 7.1, 1.1])
>>> def argsortdup(a1):
... sorted = sort(a1)
... ranked = []
... for item in a1:
... ranked.append(sorted.searchsorted(item))
... return array(ranked)
...
>>> a3 = argsortdup(a2)
>>> a2
array([ 0.1, 1.1, 2.1, 3.1, 4.1, 1.1, 6.1, 7.1, 7.1, 1.1])
>>> a3
array([0, 1, 4, 5, 6, 1, 7, 8, 8, 1])
>>>