Informatics Practices · Class 12 · NumPy
NumPyData cleaning⏱️ 5 min read
Missing Data with NaN
Real datasets have gaps. np.NaN (Not a Number) is a special floating-point value that acts as a placeholder for missing or undefined numerical data, so you can keep working with imperfect data.
1Three things to know about NaN
- It propagates: any arithmetic involving
np.NaNresults innp.NaN. This "contagious" nature means missing values are never silently ignored. - It never equals itself:
np.nan == np.nanisFalse. So you can't find NaN with==— usenp.isnan(). - It's a float: putting a NaN into an integer array converts the whole array to
float.
2Play with it
Take the array [1, 2, np.nan, 4] for a spin. Add a number to every element and watch the NaN refuse to change, then use np.isnan() to hunt it down.
Play with NaN
arr = np.array([1, 2, np.nan, 4])
1.
2.
nan
4.
Notice the trailing dot — NumPy prints array floats as 1., 2. (not 1.0). That single nan turned the whole array into floats (dtype: float64), even though we typed whole numbers.
arr + 10
np.isnan(arr)
Because np.nan != np.nan, you can’t find it with ==. Use np.isnan() instead.
playground.py
Common trap
Never test for missing values with
arr == np.nan. Because nothing equals NaN, this compares element-by-element and returns an array of all False — even at the NaN position — so it never finds anything (e.g. [False False False False]). Always reach for np.isnan(arr) instead. Quick Check
How do you correctly detect NaN values in an array?