Sub topic 5
Finding and understanding missing values
Missing values are cells with no recorded value. This chapter shows how to count them, how to judge whether they are a problem, and how to avoid common mistakes with them. It assumes you can load train.csv into a DataFrame called df, as in the previous chapters, and that you are comfortable with boolean masks and groupby.
How pandas represents missing data
When read_csv reads an empty cell, it stores a missing marker. In numeric columns the marker is NaN, which is a special floating-point value. In text columns it is also NaN, and the column keeps the object dtype. Nullable dtypes such as Int64 or string use pd.NA instead. You do not need to tell these apart for now. The methods isna() and notna() treat all of them the same way.
NaN is not equal to anything, including itself. So this filter never matches a row:
import numpy as np
print((df["Age"] == np.nan).sum())The output is 0, even though many ages are missing. Use isna() instead:
print(df["Age"].isna().sum())Counting what is missing
The first check is the one from the spine. It builds a table with a count and a percentage for each column, and it keeps only the columns that have gaps.
import pandas as pd
df = pd.read_csv("train.csv")
missing_count = df.isna().sum()
missing_pct = (df.isna().mean() * 100).round(1)
missing = pd.DataFrame({"count": missing_count, "percent": missing_pct})
print(missing[missing["count"] > 0].sort_values("count", ascending=False))Here is why it works. df.isna() returns a DataFrame of booleans with the same shape as df. Python treats True as 1, so sum() counts the gaps in each column. mean() gives the fraction of gaps, and multiplying by 100 turns that into a percentage.
On the 891-row training file you should see this:
| Column | Missing | Percent |
|---|---|---|
| Cabin | 687 | 77.1 |
| Age | 177 | 19.9 |
| Embarked | 2 | 0.2 |
The three columns have different problems, so they need different handling.
Why a value is missing matters
The count alone does not tell you what to do. Statisticians usually describe three situations:
- Missing completely at random. The gap has nothing to do with the data. A clerk's coffee spilled on a page, for example. Dropping or filling these rows does little harm.
- Missing at random. The gap depends on other columns you can see. Ages might be missing more often for third-class passengers, for example.
- Missing not at random. The gap depends on the missing value itself. People with very low incomes skipping an income question is the classic case.
You cannot prove which situation applies from the data alone. You can look for evidence, though. The usual method is to compare the rows with a gap against the rows without one.
Investigating Age
Age is missing for about one passenger in five. Create a flag column and compare survival with and without an age:
df["AgeMissing"] = df["Age"].isna()
print(df.groupby("AgeMissing")["Survived"].agg(["count", "mean"]))
print(df.groupby("Pclass")["AgeMissing"].mean().round(3))You should see that passengers with no recorded age survived less often, at about 29% against 41%. You should also see that missing ages are far more common in third class. So the gaps are not random. If you dropped every row without an age, the data would lose a disproportionate share of third-class passengers. Any survival rate you calculated afterwards would describe a different group from the whole ship.
This is the most useful habit in this chapter. Do not only ask how many values are missing. Ask who is missing.
Investigating Cabin
Cabin is missing for more than three quarters of passengers. Filling it in would mean inventing most of the column. But the gaps may carry information themselves. Try this:
df["HasCabin"] = df["Cabin"].notna()
print(df.groupby("Pclass")["HasCabin"].mean().round(3))Most first-class passengers have a recorded cabin, and very few third-class passengers do. The Cabin column is mostly a record of who had a cabin listed, which is closely tied to class and survival. If you use "has a cabin" as a feature later, remember that it partly stands in for class.
Investigating Embarked
Embarked has only two gaps, so you can read both rows instead of analyzing them statistically:
print(df.loc[df["Embarked"].isna(), ["Name", "Pclass", "Fare", "Embarked"]])With two rows, a manual decision is reasonable. Options include leaving them, filling them with the most common port, or looking up the passengers in outside records. Whatever you choose, write it down. The effect on any group-level result is tiny, but it should not be silent.
Checking for disguised missing values
isna() finds only true missing markers. Some files use placeholders such as "?", "unknown", "N/A" (which read_csv already converts by default), -1, 999, or a string of spaces. These count as real values, so they escape the check above.
Two quick ways to catch them:
print(df["Embarked"].value_counts(dropna=False))
print((df["Fare"] == 0).sum())The first lists every distinct value, including NaN, so a stray "?" stands out. The second counts zero fares. Zero is a valid number, but in this dataset it could mean either a free ticket or a missing fare. Decide which one is more plausible, check the rows, and note your reasoning. If a file uses a known placeholder, tell pandas when you load it:
df_clean = pd.read_csv("train.csv", na_values=["?", "unknown"])What to do about gaps
Choose a response column by column. None of these options is correct by default.
| Option | When it fits | Risk |
|---|---|---|
| Leave the gaps | Exploration. Many pandas methods skip `NaN` automatically. | Counts and means then rest on fewer rows than you may assume. |
| Drop rows with `dropna()` | Very few rows are affected, or the gap is clearly random. | You may remove a biased slice of the data, as with Age. |
| Drop the column | Almost everything is missing and the column is not essential. | You lose a possibly useful signal. |
| Fill with a value (`fillna`) | You need complete data for a later step. | A single fill value shrinks the spread and hides the gap. |
| Add a flag column | The gap itself may be informative. | One more column to keep consistent. |
If you do fill values, work on a copy or a new column and keep the original:
df["AgeFilled"] = df["Age"].fillna(df["Age"].median())
df["AgeMissing"] = df["Age"].isna()Filling about 20% of a column with one number creates a spike at the median in every plot of age. Filling is a modelling decision. During a first exploration, keeping the gaps and noting them is usually the more honest choice.
Common errors
- Comparing to
NaNwith==. It always givesFalse. Useisna(). - Forgetting that aggregates skip missing values.
df["Age"].mean()uses only the 714 rows that have an age. That is a reasonable default, but report it. - Dropping rows before looking. Call
dropna()only after you have checked who is missing. - Using
inplace=Trueor overwriting a raw column. You then cannot go back or compare. Create new columns. - Hiding gaps in counts.
value_counts()leaves outNaNby default. Passdropna=Falseto include it. - Averaging a boolean flag and reading it as a count. The mean of
AgeMissingis a fraction. The sum is a count.
Summary of the routine
- Build the count and percentage table.
- Look for disguised missing values with
value_counts(dropna=False)and range checks. - For each column with many gaps, create a flag and compare it against
SurvivedandPclass. - For columns with few gaps, read the rows.
- Decide, without overwriting the raw data, and record the decision.
Exercise
You create df["AgeMissing"] = df["Age"].isna() and find that passengers without an age survived at a lower rate than those with one. Does that show that being unrecorded caused lower survival? What would you check next, and how does it affect a decision to drop those rows?
Show answer
No. It shows only that the two groups differ. Missing ages are much more common in third class, which also had lower survival, so class may explain the gap. Next, compare survival for missing and non-missing ages within each class, using df.groupby(["Pclass", "AgeMissing"])["Survived"].agg(["count", "mean"]). Dropping the rows would remove a disproportionate share of third-class passengers, so any later survival rate would describe a different mix of people than the full passenger list. Keep the rows, or keep a flag column, and note the caveat.
Exercise
Why does (df["Age"] == np.nan).sum() return 0, and what should you write instead to count missing ages?
Show answer
NaN is never equal to any value, including itself, so the comparison is always False. Use df["Age"].isna().sum(), which returns 177 on the training file.