Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining 3 boolean masks in Python

I have 3 lists:

a = [True, False, True]
b = [False, False, True]
c = [True, True, False]

When I type

a or b or c

I want to get back a list that's

[True, True, True]

but I'm getting back

[True, False, True]

Any ideas on why? And how can I combine these masks?

like image 376
bard Avatar asked Nov 17 '13 04:11

bard


People also ask

How do you combine Booleans in Python?

We combine Boolean values using four main logical operators (or logical connectives): not, and, or, and ==. All decisions that can be made by Python—or any computer language, for that matter—can be made using these logical operators.

How do you merge two masks in Python?

To combine two masks with the logical_or operator, use the mask_or() method in Python Numpy. If copy parameter is False and one of the inputs is nomask, return a view of the other input mask. Defaults to False. The shrink parameter suggests whether to shrink the output to nomask if all its values are False.

What are the 3 boolean operators in Python?

There are three logical operators that are used to compare values. They evaluate expressions down to Boolean values, returning either True or False . These operators are and , or , and not and are defined in the table below.

How do you make a boolean mask in Python?

To create a boolean mask from an array, use the ma. make_mask() method in Python Numpy. The function can accept any sequence that is convertible to integers, or nomask. Does not require that contents must be 0s and 1s, values of 0 are interpreted as False, everything else as True.


2 Answers

Your or operators are comparing the lists as entire objects, not their elements. Since a is not an empty list, it evaluates as true, and becomes the result of the or. b and c are not even evaluated.

To produce the logical OR of the three lists position-wise, you have to iterate over their contents and OR the values at each position. To convert a bunch of iterables into a list of their grouped elements, use zip(). To check if any element in an iterable is true (the OR of its entire contents), use any(). Do these two at once with a list comprehension:

mask = [any(tup) for tup in zip(a, b, c)]
like image 63
jscs Avatar answered Oct 20 '22 19:10

jscs


How about this:

from numpy import asarray as ar

a = [True, False, True]
b = [False, False, True]
c = [True, True, False]

Try:

>>> ar(a) | ar(b) | ar(c)                  #note also the use `|` instead of `or`
array([ True, True, True], dtype=bool)

So no need for zip etc.

like image 44
Developer Avatar answered Oct 20 '22 17:10

Developer