Skip to content

numpy/compare-to-nan

Pack Severity Fix Versions
NumPy error unsafe, with xpd check --fix --unsafe-fixes All versions

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.

The membership rule requires a NumPy call on the right. Membership in a Python list can succeed when the list holds the same NaN object.

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.

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

See all rules in the NumPy pack.