Home > database >  How do I combine multiple NumPy boolean arrays?
How do I combine multiple NumPy boolean arrays?

Time:10-21

I have a two-dimensional (2D) array that contains many one-dimensional (1D) arrays of random boolean values.

import numpy as np

def random_array_of_bools():
  return np.random.choice(a=[False, True], size=5)


boolean_arrays = np.array([
  random_array_of_bools(),
  random_array_of_bools(),
  ... so on
])

Assume that I have three arrays:

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

This is my desired result:

[False, False, True, False, False]

How can I achieve this with NumPy?

CodePudding user response:

Use min with axis=0:

>>> boolean_array.min(axis=0)
array([False, False,  True, False, False])
>>> 

CodePudding user response:

Use .all:

import numpy as np

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


res = arr.all(0)
print(res)

Output

[False False  True False False]

CodePudding user response:

try numpy bitwise_and =>

out_arr = np.bitwise_and(np.bitwise_and(in_arr1, in_arr2),in_arr3) 
  • Related