简体   繁体   中英

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

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.

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.

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.

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM