Home > other >  How to intersect boolean subarrays for True values?
How to intersect boolean subarrays for True values?

Time:06-07

I know that Numpy provides logical_and() which allows us to intersect two boolean arrays for True values only (True and True would yield True while True and False would yield False). For example,

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

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

However, I'm wondering how I can apply this to two subarrays in an overall array? For example, consider the array:

[[[ True,  True], [ True, False]], [[ True, False], [False,  True]]]

The two subarrays I'm looking to intersect are:

[[ True,  True], [ True, False]]

and

[[ True, False], [False,  True]]

which should yield:

[[ True, False], [False,  False]]

Is there a way to specify that I want to apply logical_and() to the outermost subarrays to combine the two?

CodePudding user response:

You can use .reduce() along the first axis:

>>> a = np.array([[[ True,  True], [ True, False]], [[ True, False], [False,  True]]])
>>> np.logical_and.reduce(a, axis=0)

array([[ True, False],
       [False, False]])

This works even when you have more than two "sub-arrays" in your outer array. I prefer this over the unpacking approach because it allows you to apply your function (np.logical_and) over any axis of your array.

CodePudding user response:

I guess you can use unpacking:

import numpy as np

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

output = np.logical_and(*a)
print(output)

# [[ True False]
#  [False False]]

CodePudding user response:

If I understand your question correctly, you are looking to do:

import numpy as np

output = np.logical_and(a[:, 0], a[:, 1])

This simply slices your arrays so that you can use logical_and the way your results suggest.

  • Related