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