inequality comparison of numpy array with nan to a scalar inequality comparison of numpy array with nan to a scalar python python

inequality comparison of numpy array with nan to a scalar


One option is to disable the relevant warnings with numpy.errstate:

with numpy.errstate(invalid='ignore'):    ...

To turn off the relevant warnings globally, use numpy.seterr.


Any comparison (other than !=) of a NaN to a non-NaN value will always return False:

>>> x < -1000array([False, False, False,  True, False, False], dtype=bool)

So you can simply ignore the fact that there are NaNs already in your array and do:

>>> x[x < -1000] = np.nan>>> xarray([ nan,   1.,   2.,  nan,  nan,   5.])

EDIT I don't see any warning when I ran the above, but if you really need to stay away from the NaNs, you can do something like:

mask = ~np.isnan(x)mask[mask] &= x[mask] < -1000x[mask] = np.nan


np.less() has a where argument that controls where the operation will be applied. So you could do:

x[np.less(x, -1000., where=~np.isnan(x))] = np.nan