Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find where a NumPy array is equal to any value in a list of values

I have an array of integers and want to find where that array is equal to any value in a list of multiple values.

This can easily be done by treating each value individually, or by using multiple "or" statements in a loop, but I feel like there must be a better/faster way to do it. I'm actually dealing with arrays of size 4000 x 2000, but here is a simplified edition of the problem:

fake = arange(9).reshape((3,3))

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

want = (fake==0) + (fake==2) + (fake==6) + (fake==8)

print want 

array([[ True, False,  True],
       [False, False, False],
       [ True, False,  True]], dtype=bool)

What I would like is a way to get want from a single command involving fake and the list of values [0, 2, 6, 8].

I'm assuming there is a package that has this included already that would be significantly faster than if I just wrote a function with a loop in Python.

like image 589
arwright3 Avatar asked Oct 23 '13 18:10

arwright3


People also ask

How do you check if all elements in a NumPy array are equal?

How to check if NumPy Array equal or not? By using Python NumPy np. array_equal() function or == (equal operator) you check if two arrays have the same shape and elements. These return True if it has the same shape and elements, False otherwise.

How do you find the location of an element in a NumPy array?

Using ndenumerate() function to find the Index of value It is usually used to find the first occurrence of the element in the given numpy array.

How do you use a ANY () or a all ()?

Use all() when you need to check a long series of and conditions. Use any() when you need to check a long series of or conditions.

How do you check if a NumPy array is in a list Python?

The variable is_in_list indicates if there is any array within he list of numpy arrays which is equal to the array to check. Save this answer.


1 Answers

The function numpy.in1d seems to do what you want. The only problems is that it only works on 1d arrays, so you should use it like this:

In [9]: np.in1d(fake, [0,2,6,8]).reshape(fake.shape)
Out[9]: 
array([[ True, False,  True],
       [False, False, False],
       [ True, False,  True]], dtype=bool)

I have no clue why this is limited to 1d arrays only. Looking at its source code, it first seems to flatten the two arrays, after which it does some clever sorting tricks. But nothing would stop it from unflattening the result at the end again, like I had to do by hand here.

like image 78
Bas Swinckels Avatar answered Sep 29 '22 11:09

Bas Swinckels