Pulse Data Hub

Handling Missing Values in Python: What Works, Tested

Missing values in Python are easy to find and easy to fix badly. A one-line dropna() or fillna() can change who is in your data and what your model learns. This guide runs five common fixes on the Titanic passenger file and measures what each one does.

Find the missing values first

Load the data and count what is missing. The file is the Titanic table that ships with seaborn (891 passengers), read from the seaborn-data repository.

import pandas as pd
df = pd.read_csv("titanic.csv")
print(df.isna().sum()[lambda s: s > 0])
print((df.isna().mean() * 100).round(1)[lambda s: s > 0])

Four columns have gaps: age 177 rows (19.9%), deck 688 (77.2%), embarked 2 and embark_town 2 (0.2% each). That is 709 of 891 rows with at least one gap.

Why dropna() on the whole table goes wrong

print(len(df.dropna()))                 # 182
print(df.dropna().survived.mean().round(3))  # 0.676
print(df.survived.mean().round(3))           # 0.384

Because deck is mostly empty, dropping every row with a gap keeps only 182 passengers, and 67.6% of them survived, against 38.4% in the full file. The rows that survive a blanket dropna() are mostly first-class passengers whose cabin was recorded, so the sample no longer looks like the data you started with. Drop on the columns you need, not on the whole frame.

Check whether the gaps are random

print(df.groupby("pclass").age.apply(lambda s: s.isna().mean()).round(3))
print(df.groupby("survived").age.apply(lambda s: s.isna().mean()).round(3))

Age is missing for 13.9% of first-class passengers, 6.0% of second-class and 27.7% of third-class. It is also missing for 22.8% of those who died and 15.2% of those who survived. The gaps follow class and outcome, so they are not random, which matters for how you fill them.

Bar chart: share of Titanic passengers with missing age: 1st class 13.9%, 2nd 6.0%, 3rd 27.7%
Age is missing far more often in third class. Data: seaborn titanic.csv.

Five ways to handle a missing age

To compare fixes fairly, put the imputer inside a scikit-learn pipeline so it is fitted on each training fold only. The model is a logistic regression on class, sex, age, siblings, parents and fare, scored with 5-fold cross-validation repeated 5 times. See our guide to cross-validation in Python for why repeating matters.

from sklearn.model_selection import cross_val_score, RepeatedStratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer

X = df[["pclass","sex","age","sibsp","parch","fare"]].copy()
X["sex"] = (X.sex == "female").astype(int)
y = df.survived
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=5, random_state=0)

def run(name, Xm, ym, imp=None):
    steps = [imp] if imp is not None else []
    steps += [StandardScaler(), LogisticRegression(max_iter=1000)]
    s = cross_val_score(make_pipeline(*steps), Xm, ym, cv=cv)
    print(f"{name}: n={len(Xm)} acc={s.mean():.3f} sd={s.std():.3f}")

keep = X.dropna().index
run("drop rows", X.loc[keep], y.loc[keep])
run("median impute", X, y, SimpleImputer(strategy="median"))
run("median + indicator", X, y, SimpleImputer(strategy="median", add_indicator=True))
run("mean impute", X, y, SimpleImputer(strategy="mean"))
run("drop age column", X.drop(columns="age"), y)

The sixth variant fills age with the median for the passenger’s class and sex. That uses no survival information, so it can be computed on the full table:

Xg = X.copy(); Xg["sex_raw"] = df.sex
Xg["age"] = Xg.age.fillna(Xg.groupby(["pclass","sex_raw"]).age.transform("median"))
run("group median", Xg.drop(columns="sex_raw"), y)

What the comparison shows

MethodRowsAccuracy
Drop rows with missing age7140.797
Median of all ages8910.793
Median plus missing-indicator column8910.796
Mean of all ages8910.793
Drop the age column8910.796
Median by class and sex8910.806

Fold-to-fold standard deviation is 0.024 to 0.032, so gaps of one or two points are within noise. The one result that stands slightly apart is the class-and-sex median, 1.3 points above the plain median. The honest reading: on this file, how you fill age changes accuracy by about a point, and removing age entirely costs nothing measurable because sex and class carry most of the signal. The “drop rows” score is also on a different, smaller set of passengers (714), so it is not strictly comparable.

Filling with the overall median also shrinks the spread of ages, from a standard deviation of 14.53 to 13.02. That hardly matters for a model on this data, but it would distort any later analysis of how ages vary.

Rules for handling missing data

  • Count and plot the gaps before choosing a fix. Ask whether they follow another column.
  • Never fill using the whole dataset before splitting. Keep the imputer inside the pipeline so test rows do not leak into the fill value.
  • Prefer group-based fills (here: class and sex) over one global number when the gap is not random.
  • Add a missing-indicator column when the fact that a value is missing could carry information. Here, passengers with no age survived at 29.4% against 40.6% for those with a known age.
  • Drop a column when most of it is empty (deck is 77% missing) and drop rows only for columns you truly need.

For the full list of pandas options see the pandas missing data guide and the SimpleImputer documentation. Related reading on this site: cleaning and preprocessing data, feature engineering that helps, tested and pandas groupby.

FAQ

Should I always impute missing values?

No. If few rows are affected and the gaps look random, dropping them is fine. If many rows are affected, or the gaps follow another column as they do here, drop-all discards a biased slice of the data.

Is the mean or the median better for filling?

The median is less affected by extreme values. On this data mean and median gave the same accuracy (0.793), so the choice made no measurable difference.

What does the missing-indicator do?

It adds a 0/1 column marking which rows were filled, so the model can use the fact of missingness. Here it moved accuracy from 0.793 to 0.796, within noise.

Does this carry over to other datasets?

Not automatically. These numbers come from one file and one model. The method (compare fixes inside a pipeline with repeated cross-validation) is what carries over. Versions used: pandas 3.0.5 and scikit-learn 1.9.1.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights