Search code examples
pythonarraysnumpyboolean-expression

NumPy chained comparison with two predicates


In NumPy, I can generate a boolean array like this:

>>> arr = np.array([1, 2, 1, 2, 3, 6, 9])
>>> arr > 2
array([False, False, False, False,  True,  True,  True], dtype=bool)

How can we chain comparisons together? For example:

>>> 6 > arr > 2
array([False, False, False, False,  True,  False,  False], dtype=bool)

Attempting to do so results in the error message

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


Solution

  • AFAIK the closest you can get is to use &, |, and ^:

    >>> arr = np.array([1, 2, 1, 2, 3, 6, 9])
    >>> (2 < arr) & (arr < 6)
    array([False, False, False, False,  True, False, False], dtype=bool)
    >>> (2 < arr) | (arr < 6)
    array([ True,  True,  True,  True,  True,  True,  True], dtype=bool)
    >>> (2 < arr) ^ (arr < 6)
    array([ True,  True,  True,  True, False,  True,  True], dtype=bool)
    

    I don't think you'll be able to get a < b < c-style chaining to work.