Say I have an array:
JavaScript
x
3
1
import numpy as np
2
arr = np.random.randint(0, 5, 20)
3
then arr>3
results in an array of type bool with shape (20,). How can I most efficiently do the same thing with the “contains” operator? The simple
JavaScript
1
2
1
arr in [2, 4]
2
will result in “The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()”. Is there another way than
JavaScript
1
2
1
np.array([ x in [2, 4] for x in arr])
2
?
Advertisement
Answer
You can use np.isin
:
JavaScript
1
4
1
import numpy as np
2
arr = np.random.randint(0, 5, 20)
3
np.isin(arr, [2, 4])
4
Output:
JavaScript
1
4
1
array([False, True, False, False, False, True, False, False, True,
2
False, False, False, True, False, False, True, False, True,
3
True, True])
4
The function returns a boolean array of the same shape as your input array named arr
that is True
where an element of arr
is in your second list argument [2, 4]
and False
otherwise