Skip to content
Advertisement

element wise “contains” in Python

Say I have an array:

JavaScript

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

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

?

Advertisement

Answer

You can use np.isin:

JavaScript

Output:

JavaScript

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement