Find IDs (or indices) of a np array in the sorted array, with possible repetitive elements

247 Views Asked by At

I have a 1D numpy array

x=np.array([0.1,0.3,0.2,0.4,0.5,0.4])

I need to calculate another array of the same size, where each element is the ID (or called index) in the sorted array. Here the sorted array would be [0.1,0.2,0.3,0.4,0.5]. Thus, 0.1 corresponds to ID 0; 0.2 corresponds to ID 1;...0.5 corresponds to ID 4. The expected result will be

    [0,2,1,3,4,3]

Note that this question is similar to, but different from How to get the index of the sorted list for the original list in Python? as we need to deal with repetitive elements.

3

There are 3 best solutions below

1
Quang Hoang On BEST ANSWER

You can use np.unique:

uniques, out = np.unique(x, return_inverse=True)

Output (out):

array([0, 2, 1, 3, 4, 3])

That said, working with unique floats should generally be avoided.

1
flabons On

Just use

import numpy as np
x=np.array([0.1,0.3,0.2,0.4,0.5,0.4])
>>> indeces=np.argsort(x)
>>> indeces
array([0, 2, 1, 3, 5, 4])
3
mathfux On

Try: np.searchsorted:

>>> x = np.array([0.1,0.3,0.2,0.4,0.5,0.4])
>>> np.searchsorted(np.unique(x), x)
array([0, 2, 1, 3, 4, 3], dtype=int32)

np.unique outputs unique items in sorted order.