pythonpandasnumpy

Perform logical OR operation on multiple NumPy arrays


I have the following code:

array1 = np.array([1,0,1,0])
array2 = np.array([1,1,0,0])

array3 = array1 | array2

array3 will be:

[1 1 1 0]

This code works fine but I would like to extend it to more arrays without writing out array1 | array2 | array3 | etc.

Anyone know an efficient way of doing this? Possibly using .any()?


Solution

  • I would stick to NumPy here, but there are a few ways of doing it. Here's using logical_or.reduce.

    np.logical_or.reduce([array1, array2])
    # array([ True,  True,  True, False])
    

    Another variant is using using column_stack and any:

    np.column_stack([array1, array2]).any(axis=1)
    # array([ True,  True,  True, False])