Search code examples
pythonarraysnumpybooleanlogical-operators

How to get the relative complement of a boolean numpy array and another?


Let's say I have two numpy arrays:

>>> v1
array([ True, False, False, False,  True])
>>> v2
array([False, False,  True,  True,  True])

I'm trying to retrieve an array that has the same length (5) and contains True in each position where v1==True AND v2==False. That would be:

array([True, False,  False,  False,  False])

Is there a quick way in numpy, something like logical_not() but considering v1 as the reference and v2 as the query?


Solution

  • You just need to use the right bitwise operators:

    v1 & ~v2
    # array([ True, False, False, False, False])