zell
zell

Reputation: 10204

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.

Upvotes: 2

Views: 321

Answers (3)

mathfux
mathfux

Reputation: 5949

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.

Upvotes: 1

flabons
flabons

Reputation: 331

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

Upvotes: -1

Quang Hoang
Quang Hoang

Reputation: 150745

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.

Upvotes: 2

Related Questions