Almost every real dataset has missing values: a customer who skipped a survey question, a sensor that went offline, a form field added halfway through the year. Pandas marks them as NaN (or None, NaT for dates, <NA> for nullable types). Most calculations quietly skip them, and many machine learning models refuse to run on them at all.
Handling missing values is a judgement call, not a single command. This lesson shows how to find them, how to think about why they're missing, and the main ways to deal with them: dropping, filling with a typical value, filling by group, and flagging.
Find missing values
We'll use the Titanic dataset, which has plenty:
Download the data: titanic.csv (58 KB), or from the original source, the seaborn-data repository on GitHub. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("titanic.csv").
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
titanic = sns.load_dataset("titanic")
missing = pd.DataFrame({
"missing": titanic.isna().sum(),
"percent": (titanic.isna().mean() * 100).round(1),
})
print(missing[missing["missing"] > 0].sort_values("missing", ascending=False))
missing percent
deck 688 77.2
age 177 19.9
embarked 2 0.2
embark_town 2 0.2
isna() gives True for each missing cell. sum() counts the Trues per column, and mean() gives the share, because True counts as 1.
A chart makes the picture obvious when there are many columns:
pct = titanic.isna().mean().sort_values() * 100
fig, ax = plt.subplots()
ax.barh(pct.index, pct.values)
ax.set_xlabel("Missing values (%)")
ax.set_title("Missing values by column")
plt.show()
Hidden missing values
Not every missing value is NaN. Datasets often use placeholders such as 0, -1, 999, "?", "N/A", "unknown" or an empty string. They don't show in isna(), and they ruin averages. Look for them with value_counts() and describe(), then convert them to real missing values:
survey = pd.DataFrame({"age": [25, 31, 999, 42, -1],
"city": ["Kanpur", "?", "Pune", "", "Delhi"]})
survey = survey.replace({"age": {999: np.nan, -1: np.nan},
"city": {"?": np.nan, "": np.nan}})
print(survey)
print(survey.isna().sum())
age city
0 25.0 Kanpur
1 31.0 NaN
2 NaN Pune
3 42.0 NaN
4 NaN Delhi
age 2
city 2
dtype: int64
When loading a CSV, pd.read_csv("file.csv", na_values=["?", "N/A", "unknown"]) does this as the file is read.
Why are values missing?
Before choosing a fix, ask why. Statisticians describe three situations:
| Type | Meaning | Example | Risk of simple fixes |
|---|---|---|---|
| Missing completely at random | Missingness has nothing to do with any data | A lab sample was dropped | Low |
| Missing at random | Missingness depends on other columns you have | Ages were recorded less often for third-class passengers | Medium: fill using those columns |
| Missing not at random | Missingness depends on the missing value itself | People with high incomes skip the income question | High: any fill is biased |
You can test some of this. Did passengers with a missing age survive at a different rate?
print(titanic.groupby(titanic["age"].isna())["survived"].mean().round(3))
age
False 0.406
True 0.294
Name: survived, dtype: float64
Passengers with an unknown age survived less often (29% against 41%). Ages were more often unknown for third-class passengers, who survived less. So the missingness carries information, and that's worth keeping, as you'll see in the flagging section.
Option 1: drop
print(len(titanic.dropna())) # rows with no missing value at all
print(len(titanic.dropna(subset=["embarked"]))) # rows missing embarked only
print(titanic.drop(columns="deck").shape)
182
889
(891, 14)
dropna()with no arguments drops a row if any column is missing. Here it would keep only 182 of 891 passengers. Almost never what you want.dropna(subset=[...])drops rows missing specific columns: fine forembarked, where only 2 rows are affected.- Dropping a column makes sense when most of it is missing, like
deckat 77%.
A rough guide: dropping rows is fine when they're a small share (a few percent) and missing at random. Otherwise it throws away information and can bias results.
Option 2: fill with a typical value
ages = titanic["age"]
print(round(ages.mean(), 2), ages.median(), titanic["embarked"].mode()[0])
29.7 28.0 S
| Column type | Fill with | Code |
|---|---|---|
| Numeric, roughly symmetric | Mean | df["col"].fillna(df["col"].mean()) |
| Numeric, skewed or with outliers | Median | df["col"].fillna(df["col"].median()) |
| Categorical | Mode (most common value) | df["col"].fillna(df["col"].mode()[0]) |
| Categorical, many missing | A new "Unknown" label | df["col"].fillna("Unknown") |
Filling is easy, but it has a cost. Watch what happens to the age distribution when 177 ages all become 28:
filled = ages.fillna(ages.median())
fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
axes[0].hist(ages.dropna(), bins=30, edgecolor="white")
axes[0].set_title("Original ages (missing left out)")
axes[1].hist(filled, bins=30, edgecolor="white")
axes[1].set_title("Missing ages filled with the median")
plt.show()
A tall false spike at 28. The spread shrinks, and relationships with other columns weaken, because 177 people now share one made-up age.
Option 3: fill by group
A smarter fill uses related columns. Passengers in different classes had different typical ages, so fill each missing age with the median of its own class and sex:
group_median = titanic.groupby(["pclass", "sex"])["age"].transform("median")
titanic["age_filled"] = titanic["age"].fillna(group_median)
print(titanic.groupby(["pclass", "sex"])["age"].median().unstack())
sex female male
pclass
1 35.0 40.0
2 28.0 30.0
3 21.5 25.0
transform("median") returns, for every row, the median of that row's group, so fillna can fill row by row. Missing ages now become six different, more realistic values instead of one.
For time series, filling from neighbours often makes most sense: ffill() copies the last known value forward, and interpolate() draws a straight line between known values.
Option 4: flag, then fill
Because missingness can carry information, keep a record of it in a new column before filling:
titanic["age_was_missing"] = titanic["age"].isna().astype(int)
print(titanic["age_was_missing"].sum())
177
A model can then learn from both the filled age and the fact that it was missing. This simple trick often helps.
Choosing a method
| Situation | Good choice |
|---|---|
| A few rows missing, at random | Drop those rows |
| Most of a column missing | Drop the column, or keep only a "was missing" flag |
| Numeric column, some missing | Median (or group median) plus a flag |
| Category column | Mode, or a new "Unknown" category |
| Time series | ffill() or interpolate() |
| Missing not at random | Flag it, and be careful about any conclusions |
For machine learning, compute fill values on the training data only and reuse them on test data, or you leak information. Scikit-learn's SimpleImputer handles this for you.
Practice
- Count missing values in each column of
titanic, as percentages, rounded to one decimal place.
Show the answer
print((titanic.isna().mean() * 100).round(1))
- Fill the two missing
embarkedvalues with the most common port.
Show the answer
titanic["embarked"] = titanic["embarked"].fillna(titanic["embarked"].mode()[0])
The mode is "S", Southampton.
- A column
incomeis missing for 30% of customers, and you suspect wealthy customers skip the question. Is filling with the median a good idea?
Show the answer
Not on its own. It's probably missing not at random, so the median would understate incomes for those customers. Add a "was missing" flag, consider an "unknown" group in the analysis, and state the limitation in your findings.
Interview questions
How do you find missing values in pandas?
df.isna().sum() counts them per column and df.isna().mean() gives the share. Also look for placeholder values like 0, -1, 999 or "?" with value_counts() and describe(), and convert them to NaN.
When would you use the median instead of the mean to fill missing values?
When the column is skewed or has outliers, because the median isn't pulled by extreme values.
What are the downsides of filling missing values with a single value?
It creates an artificial spike, shrinks the variance, weakens relationships with other variables, and hides the fact that values were missing. Group-based filling, model-based imputation and missingness flags reduce these problems.
What to learn next
- Find unusual values in detect and treat outliers.
- Revisit first look at a dataset.