python - Find unsorted indices after using numpy.searchsorted -
i have large (millions) array of id numbers ids
, , want find indices array of targets (targets
) exist in ids
array. example, if
ids = [22, 5, 4, 0, 100] targets = [5, 0]
then want result:
>>> [1,3]
if pre-sort array of ids
, it's easy find matches using numpy.searchsorted
, e.g.
>>> 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 find reverse mapping 'unsort' result? i.e. map sorted entries @ [2,0]
before: [1,3]
.
there few answers dancing around already, make clear need use 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])
Comments
Post a Comment