Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersect two boolean arrays for True

Tags:

Having the numpy arrays

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

how can I make the intersection of the two so that only the True values match? I can do something like:

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

but the last item is True (understandably because both are False), whereas I would like the result array to be True only in the 4th element, something like:

array([False, False, False,  True,  False], dtype=bool)
like image 951
PedroA Avatar asked Jun 15 '17 23:06

PedroA


People also ask

How do you add two boolean arrays in Python?

add 's third parameter is an optional array to put the output into. The function can only add two arrays. Adding boolean arrays does not produce integer arrays, you need to cast manually for that.

How do you make a boolean mask?

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.

What is boolean masking?

Boolean masking is typically the most efficient way to quantify a sub-collection in a collection. Masking in python and data science is when you want manipulated data in a collection based on some criteria. The criteria you use is typically of a true or false nature, hence the boolean part.

What is mask in array?

A masked array is the combination of a standard numpy. ndarray and a mask. A mask is either nomask , indicating that no value of the associated array is invalid, or an array of booleans that determines for each element of the associated array whether the value is valid or not.


1 Answers

Numpy provides logical_and() for that purpose:

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

c = np.logical_and(a, b)
# array([False, False, False, True, False], dtype=bool)

More at Numpy Logical operations.

like image 74
zwer Avatar answered Sep 18 '22 06:09

zwer