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
all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.
You can search an array for a certain value, and return the indexes that get a match. To search an array, use the where() method.
Python has a method to search for an element in an array, known as index(). If you would run x. index('p') you would get zero as output (first index).
For big arrays xs
and ys
, you would need to change the basic approach for this to become fast. If you are fine with sorting xs
, then an easy option is to use numpy.searchsorted()
:
xs.sort()
ndx = numpy.searchsorted(xs, ys)
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:
orig_indices = xs.argsort()
ndx = orig_indices[numpy.searchsorted(xs[orig_indices], ys)]
In this kind of cases, just easily use np.isin()
function to mask those elements conform your conditions, like this:
xs = np.asarray([45, 67, 32, 52, 94, 64, 21])
ys = np.asarray([67, 94])
mask=xs[np.isin(xs,xy)]
print(xs[mask])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With