Search code examples
pythonarraysnumpymasking

Mask numpy array evaluating nan as True


Consider a numpy array with the data:

aa = np.array([-4.793, -1.299, 0.453, np.nan, np.nan, 1.131, 0.684,  1.037])

I need to create a mask like so:

mask = -4. < aa

which evaluates to

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

Here's the catch: I need the nan values to evaluate to True.

I'm after a general solution that does not involve modifying my input array aa.


Solution

  • It's quite simple with a logic function

    import numpy as np
    
    aa = np.array([-4.793, -1.299, 0.453, np.nan, np.nan, 1.131, 0.684,  1.037])
    
    mask = np.logical_or(-4 < aa, np.isnan(aa))
    
    print mask
    # [False  True  True  True  True  True  True  True]