I am looking for a numpy function to find the indices at which certain values are found within a vector (xs). The values are given in another array (ys). The returned indices must follow the order of ys.
In code, I want to replace the list comprehension below by a numpy function.
>> import numpy as np
>> xs = np.asarray([45, 67, 32, 52, 94, 64, 21])
>> ys = np.asarray([67, 94])
>> ndx = np.asarray([np.nonzero(xs == y)[0][0] for y in ys]) # <---- This line
>> print(ndx)
[1 4]
Is there a fast way?
Thanks
For big arrays
xsandys, you would need to change the basic approach for this to become fast. If you are fine with sortingxs, then an easy option is to usenumpy.searchsorted():If it is important to keep the original order of
xs, you can use this approach, too, but you need to remember the original indices: