Handling Missing Values (NaN)
Detect, remove, and fill missing values — critical for accurate analysis
Missing values (NaN — Not a Number) are present in almost every real dataset. How you handle them affects every calculation. Ignoring nulls gives wrong counts. Summing columns with nulls gives wrong totals in some contexts. Choosing how to fill or drop nulls requires business judgment — not just a formula.
Pandas represents missing values as NaN (for numbers) and NaT (for dates). Both are treated consistently by pandas functions.
Example
Key Points
- ✓df.isnull().sum() is the first null check — run it on every new dataset
- ✓dropna() without parameters drops any row with even one null — often too aggressive
- ✓fillna(median()) for numeric skewed data; fillna(mean()) for normally distributed
- ✓fillna(method="ffill") fills with the previous valid value — for time-series data
- ✓NaN arithmetic: any operation on NaN returns NaN — so one null in a column skews nothing (pandas skips NaN in sum/mean by default)
Practice Question
A "City" column has 30% null values. What is the most appropriate way to handle them?