Home > other >  In a binary numpy array, how to change a row to value True , If all elements of that row is False?
In a binary numpy array, how to change a row to value True , If all elements of that row is False?

Time:03-05

Suppose I have a numpy array as follows

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

As we can see the second row is all false, since all of the elements of the second row is false we want to transform all of it to True such as

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

I can do this with for loop, but I am looking something which will be efficient

CodePudding user response:

Use any on row axis and reverse the mask:

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

a[~a.any(axis=1)] = True

Output:

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

Details:

>>> a.any(axis=1)
array([ True, False,  True])  # which rows contain at least 1 True

>>> ~a.any(axis=1)
array([False,  True, False])  # so which rows have only False

>>> a[~a.any(axis=1)]
array([[False, False, False]])  # second row of your array
  • Related