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.
>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]