Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading