Search code examples
pythonnumpyboolean-operations

How to perform element-wise Boolean operations on NumPy arrays


For example, I would like to create a mask that masks elements with value between 40 and 60:

foo = np.asanyarray(range(100))
mask = (foo < 40).__or__(foo > 60)

Which just looks ugly. I can't write

(foo < 40) or (foo > 60)

because I end up with:

  ValueError Traceback (most recent call last)
  ...
  ----> 1 (foo < 40) or (foo > 60)
  ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Is there a canonical way of doing element-wise Boolean operations on NumPy arrays with good looking code?


Solution

  • Try this:

    mask = (foo < 40) | (foo > 60)
    

    Note: the __or__ method in an object overloads the bitwise or operator (|), not the Boolean or operator.