Python: Adding boolean Numpy arrays

11,918

Solution 1

>>> a=[True, True, False, False]
>>> b=[False, False, False, False]
>>> c=[False, False, False, True]
>>> map(sum, zip(a,b,c))
[1, 1, 0, 1]
>>>

Solution 2

np.add's third parameter is an optional array to put the output into. The function can only add two arrays.

Just use the normal operators (and perhaps switch to bitwise logic operators, since you're trying to do boolean logic rather than addition):

d = a | b | c

If you want a variable number of inputs, you can use the any function:

d = np.any(inputs, axis=0)

Solution 3

I am personally using the np.logical_and function.

For the problem proposed:

In [3]: a = np.array([True, True, False, False])
   ...: b = np.array([False, False, False, False])
   ...: c = np.array([False, False, False, True])

In [4]: np.logical_and(a,b,c)
Out[4]: array([False, False, False, False], dtype=bool)

Solution 4

There is also the straightforward solution

a + b + c

resulting in

array([ True,  True, False,  True], dtype=bool)
Share:
11,918
Joe Flip
Author by

Joe Flip

I'm an astrophysics PhD working on the NIRISS team for the James Webb Space Telescope. My research interests are primarily brown dwarfs and exoplanets. I'm a self-taught Python programmer still with much to learn!

Updated on June 05, 2022

Comments

  • Joe Flip
    Joe Flip almost 2 years

    I have three lists as such:

    a = np.array([True, True, False, False])
    b = np.array([False, False, False, False])
    c = np.array([False, False, False, True])
    

    I want to add the arrays so that the new array only has False if all the corresponding elements are False. For example, the output should be:

    d = np.array([True, True, False, True])
    

    However, d = np.add(a,b,c) returns:

    d = np.array([True, True, False, False])
    

    Why is this and how can I fix it? Thanks!