NaN represents an undefined or indeterminate numeric result, like 0 divided by 0 or the square root of a negative real number, and it has the unusual property of never being equal to anything, including itself — which is exactly why you can't detect it with a plain equality check against np.nan. isnan() instead inspects the actual floating-point bit pattern to correctly identify NaN values, regardless of that equality quirk.
1Understanding np.isnan()
NaN represents an undefined or indeterminate numeric result, like 0 divided by 0 or the square root of a negative real number, and it has the unusual property of never being equal to anything, including itself — which is exactly why you can't detect it with a plain equality check against np.nan. isnan() instead inspects the actual floating-point bit pattern to correctly identify NaN values, regardless of that equality quirk.
Never compare an array directly for equality against np.nan to detect NaN values — since NaN never equals anything, including itself, that comparison always evaluates to False even where NaN is genuinely present; use np.isnan(arr) instead.
import numpy as np
arr = np.array([1.0, np.nan, 3.0])
print(np.isnan(arr))2Practical Example
Here is a real-world application of np.isnan() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([1.0, np.nan, 3.0, np.nan])
print(arr == np.nan)
print(np.isnan(arr))3Best Practices
Follow these guidelines when working with np.isnan():
1. Always use np.isnan(arr) to detect NaN values, never a direct equality comparison to np.nan
2. Combine np.isnan() with boolean indexing to filter out or replace missing/invalid data represented as NaN
3. Use np.nan_to_num() when you need to replace NaN, and optionally inf, values with a specific substitute in one call
Tip: Never compare an array directly for equality against np.nan to detect NaN values — since NaN never equals anything, including itself, that comparison always evaluates to False even where NaN is genuinely present; use np.isnan(arr) instead.
import numpy as np
arr = np.array([1.0, np.nan, 3.0])
print(np.isnan(arr))