Sub topic 5
Finding and understanding missing values
This chapter assumes you can run Python in a notebook or script and that df already holds the Titanic training data from pd.read_csv("train.csv"). It also assumes you know what a DataFrame and a boolean mask are.
What "missing" means in pandas
pandas marks an absent value as NaN (not a number). It appears in numeric columns, and in text columns as NaN or None. The method isna() returns True for every such cell. Any tool that skips or counts missing values relies on this marker.
The first look with df.info() already hints at the problem. Any column whose non-null count is below the row count has gaps.
Counting missing values
Chain isna() with sum() to count gaps per column. Chain it with mean() to get the share of rows, because True counts as 1.
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))The final line filters with a boolean mask so only columns with gaps are shown. Sorting puts the worst columns first. On the standard training file you should see roughly these results:
| Column | Missing | Approx. share |
|---|---|---|
| Cabin | 687 | 77% |
| Age | 177 | 20% |
| Embarked | 2 | 0.2% |
Why values are missing
The cause of a gap decides what you may safely do about it. Ask this for each column:
- Cabin: Most passengers have no recorded cabin. Many third-class passengers likely had no assigned cabin, or the record was lost. Missingness may itself carry information.
- Age: About one passenger in five has no age. The records were probably incomplete, and the gaps may not be spread evenly across classes.
- Embarked: Two missing values is a data entry gap, not a pattern.
You can test whether gaps are related to other columns by grouping on the missing flag:
print(df.groupby(df["Age"].isna())["Survived"].agg(["count", "mean"]))
print(df.groupby("Pclass")["Age"].apply(lambda s: s.isna().mean()).round(2))If the survival rate differs between rows with and without an age, or the missing share varies by class, the gaps are not random. Dropping or filling them will then change your results.
Options for handling gaps
During exploration, prefer the least invasive option:
- Leave them in. Methods such as
mean(),describe()andgroupbyskipNaNby default. This is often enough. - Add a flag.
df["AgeMissing"] = df["Age"].isna()keeps the information that a value was absent. - Drop rows.
df.dropna(subset=["Embarked"])is reasonable for two rows. Applied to Cabin, it would remove most of the data. - Fill values.
df["Age"].fillna(df["Age"].median())makes every row usable, but it invents data and shrinks the spread of ages.
Common errors
- Counting only
df.isna().sum().sum(). The total hides which columns are affected. - Treating
0or"unknown"as present. These are not detected byisna(). Check suspicious placeholders withvalue_counts(). - Comparing with
== np.nan. This is alwaysFalse. Useisna(). - Forgetting that
groupbydrops rows whose key is missing unless you passdropna=False.
Exercise
Age is missing for 177 of 891 rows. You compute the mean survival rate for rows with a missing age and for rows with a known age, and the two rates differ. Why does this matter for filling Age with the median?
Show answer
The difference shows the gaps are related to survival, so they are not random. Filling every gap with one median treats those passengers as typical, which can bias later comparisons. Keep a missing flag or fill in a separate column and state the caveat.
Exercise
Write one line that returns the percentage of missing values in the Cabin column only.
Show answer
df["Cabin"].isna().mean() * 100