Missing Data with NaN
🎬 Watch the 3:18 video of this topic ↓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. Write it in small letters: older books use np.NaN, which NumPy 2 removed (it now stops with an AttributeError).
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.
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.
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.How do you correctly detect NaN values in an array?
Missing Data: NaN, in 3:18
One animated video of this topic, narrated. Watch it before the lessons for the big picture, or after them to revise.
🔊 Hindi mein sunna hai? Watch on YouTube with Hindi audio ↗(there, choose ⚙ Settings → Audio track → Hindi)