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

Numpy logically merging boolean arrays with numpy.NaN

Let’s say I have 2 numpy arrays. The first one will always contain ONLY True or False values. The second may contain True or False, or it could have numpy.NaN. I want to merge the 2 arrays such that if the second array doesn’t have a True or False value (it’s value is numpy.NaN), it will take the value from the same location as the first array, otherwise, it will take on the True or False value. Confusing? Great! Here are some examples:

# example 1
a1 = np.array([True, False, True, False, True], dtype=object)
a2 = np.array([np.NaN, np.NaN, np.NaN, np.NaN, np.NaN], dtype=object)
output = a1.combinaficate(a2)
# prints [True, False, True, False, True]

# example 2
a1 = np.array([True, False, True, False, True], dtype=object)
a2 = np.array([np.NaN, True, np.NaN, False, np.NaN], dtype=object)
output = a1.combinaficate(a2)
# prints [True, True, True, False, True]

# example 3
a1 = np.array([True, True, True, True, True], dtype=object)
a2 = np.array([np.NaN, np.NaN, np.NaN, False, np.NaN], dtype=object)
output = a1.combinaficate(a2)
# prints [True, True, True, False, True]

# example 4
a1 = np.array([False, False, False, False, False], dtype=object)
a2 = np.array([np.NaN, np.NaN, True, False, np.NaN], dtype=object)
output = a1.combinaficate(a2)
# prints [False, False, True, False, False]

I know that I could write a for loop, but the spirit of the question is "Is there a way to use strictly numpy to make this computation?".

Thank you.

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 :

How about this? The casting is necessary because np.isnan doesn’t like booleans. You could also use pd.isnull and not do the casting if you are willing to use pandas.

output = a2.copy()
idx = np.isnan(a2.astype(np.float16))
output[idx] = a1[idx]
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