Skip to content

numpy/compare-to-nan

Rule compare-to-nan
Pack NumPy
Severity error
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

A comparison with NaN is False for every value, NaN included. Use np.isnan to find NaN.

missing = x == np.nan
missing = np.isnan(x)

The rule reports x == np.nan, x != np.nan, x == float("nan"), x == math.nan and np.nan in np.unique(x). None of them finds NaN, because NaN equals nothing.

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes np.isnan(x), np.isnan(np.unique(x)).any() for np.nan in np.unique(x), and not np.isnan(np.unique(x)).any() for not in. isnan raises on an array of text or objects, where in returned False.

In a file that imports pandas, the pandas rule compare-to-missing reports the code instead. The rule leaves a comparison alone that is passed to an assert function, because a test may check how a comparison with NaN behaves.

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

A comparison with NaN is False for every value, NaN included. Write $NP.isnan($X).

Browse the other rules of the NumPy pack.