Find unsorted indexes after using numpy.searchsorted

I have a large (millionth) array of identification numbers ids, and I want to find indexes where idsanother array of targets ( targets) exists in the array . For example, if

ids = [22, 5, 4, 0, 100]
targets = [5, 0]

then I want to get the result:

>>> [1,3]

If I pre-sort the array ids, then it is easy to find matches using numpy.searchsorted, for example.

>>> ids = np.array([22, 5, 4, 0, 100])
>>> targets = [5, 0]
>>> sort = np.argsort(ids)
>>> ids[sort]
[0,4,5,22,100]
>>> np.searchsorted(ids, targets, sorter=sort)
[2,0]

But how can I find the inverse mapping for the "unsort" of this result? That is to match the sorted records in the [2,0]back where they were before: [1,3].

+4
source share
4

, , , , , sort[rank].

# Setup
ids = np.array([22, 5, 4, 0, 100])
targets = np.array([5, 0])

sort = np.argsort(ids)
rank = np.searchsorted(ids, targets, sorter=sort)
print(sort[rank])
# array([1, 3])
+5

?

sort[np.searchsorted(ids, targets, sorter=sort)]

:

np.hstack([np.where(ids==x)[0] for x in targets])

:

array([1, 3])
+1

, - .

"" : key = numpy.arange(len(ids)) , : revsort = key[np.argsort(ids)]


edit: @birico, key[sort] sort!

>>> sort = np.argsort(ids)
>>> ids[sort]
[0,4,5,22,100]
>>> found = np.searchsorted(ids, targets, sorter=sort)
>>> found
[2,0]
>>> sort[found]
[1,3]
+1

broadcasting -

_,out = np.where(np.array(ids)==np.array(targets)[:,None])

-

In [20]: ids
Out[20]: [22, 5, 4, 0, 100]

In [21]: targets
Out[21]: [0, 22, 5]

In [22]: _,out = np.where(np.array(ids)==np.array(targets)[:,None])

In [23]: out
Out[23]: array([3, 0, 1], dtype=int64)
0

All Articles