Lesson 5 of 11 · 2 min
Step 3 — Handle Missing Values
5 strategies:
Strategy 1: Mean/Median/Mode Imputation
import matplotlib.pyplot as plt # Numeric — use median (robust to outliers) median_age = df['Age'].median() df['Age_filled'] = df['Age'].fillna(median_age) # Verify distribution didn't shift badly df['Age'].plot(kind='kde', label='original') df['Age_filled'].plot(kind='kde', label='filled') plt.legend() plt.show() # Output: plot showing two overlapping curves # Categorical — use mode mode_embarked = df['Embarked'].mode()[0] df['Embarked'] = df['Embarked'].fillna(mode_embarked)
Advantages: Easy, fast
Disadvantages: Distorts variance, weakens correlations
Strategy 2: Drop Rows/Columns
# Drop rows with any missing value
df_clean = df.dropna()
print(df.shape) # Output: (891, 12)
print(df_clean.shape) # Output: (183, 12) — fewer rows
# Drop column if >50% missing
df.drop('Cabin', axis=1, inplace=True) # 687/891 = 77% missing
Use when: column has >50% missing, or dataset is large enough to afford row drops.
Strategy 3: Random Sample Imputation
# Fill missing with random sample from existing values sample = df['Age'].dropna().sample(df['Age'].isnull().sum(), random_state=42) sample.index = df[df['Age'].isnull()].index df.loc[df['Age'].isnull(), 'Age'] = sample
Use when: you want to preserve the original distribution.
Strategy 4: Flag + Fill
# Create indicator column FIRST, then fill df['Age_missing'] = df['Age'].isnull().astype(int) df['Age'] = df['Age'].fillna(df['Age'].median())
Use when: missingness itself is informative (e.g., missing age might correlate with survival).
