5

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!

4 Answers 4

13

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Adding boolean arrays does not produce integer arrays, you need to cast manually for that.
What the... huh. You're right. I could've sworn it did. Fixed.
6

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)

Comments

5

There is also the straightforward solution

a + b + c

resulting in

array([ True,  True, False,  True], dtype=bool)

Comments

-4
>>> 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]
>>>

2 Comments

This works best for me since I can pass a variable number of arrays to add up. I.e. map(bool,map(sum, zip(*X))) where X = [a,b,c,...]. Thanks!
@JoeFlip: This is using lists instead of numpy arrays. Performance will tank, the broadcasting semantics will vanish, and slices won't work right. np.any is a better choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.