Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find multiple values within a Numpy array

Tags:

python

numpy

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

like image 437
Hernan Avatar asked Mar 05 '12 12:03

Hernan


People also ask

What does .all do in NumPy?

all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.

How do you find something in an array in Python?

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.

How do you find numbers in an array Python?

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


2 Answers

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)]
like image 138
Sven Marnach Avatar answered Sep 29 '22 11:09

Sven Marnach


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])
like image 35
farshad madani Avatar answered Sep 29 '22 10:09

farshad madani