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

Python Numpy 'Invert' Boolean Mask Operation

When I have an array a and a boolean mask b, I can find the ‘masked’ vector c.

a = np.array([1, 2, 4, 7, 9])
b = np.array([True, False, True, True, False])

c = a[b]

Now suppose, it’s the other way around. I have c and b and would like to arrive at d (below). What is the easiest way to do this?

c = np.array([1, 4, 7])
b = np.array([True, False, True, True, False])

d = np.array([1, 0, 4, 7, 0])

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 :

You could use:

d = np.zeros_like(b, dtype=c.dtype)
d[b] = c

Output: array([1, 0, 4, 7, 0])

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