Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 8/ 160
01. Python & Data Wrangling

Handling Missing Values

Detect NaNs/nulls, choose drop vs impute strategies, and avoid silent leakage from fill methods.

Beginnerisna · Drop vs Impute3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Some cells in the table are empty; you find them, figure out why, and then decide whether to remove them, fill them in or leave a note that they were missing.

Think of it like…

A survey with blank answers: a blank might mean the person skipped it by accident, wasn't asked, or didn't want to say. Treating all blanks as "average answer" ignores why they're blank, and the reason matters.

Where you’ve seen it

A loan dataset has income missing for 12 percent of applicants. Missing rates are 31 percent for self-employed applicants and 6 percent for salaried ones, so the gaps aren't random. The team adds an income_missing flag, imputes with the median within each employment type, and fits the imputer on the training split only. Dropping the rows would have removed a large share of self-employed applicants and biased the model.

Words you’ll hear

MCAR / MAR / MNAR
Missing completely at random / at random given other columns / not at random (depends on the missing value).
Imputation
Filling a missing value with an estimate such as the median, a group median or a model prediction.
Sentinel value
A placeholder like -999 or "N/A" that should be converted to a proper missing value.
Missing indicator
A boolean column recording that a value was missing, kept as a feature.

Visual diagram

Loading interactive diagram

Theory & deep dive

Detecting and diagnosing

Start with df.isna().sum() and df.isna().mean() to see counts and percentages, then hunt for disguised missing values: df["age"].value_counts().head(10) often reveals an ugly spike at 0 or 999. Convert them when reading the file (pd.read_csv(..., na_values=["N/A", "-999", "unknown"])) or with df.replace(...). Pandas also offers nullable dtypes (Int64, boolean, string) that use pd.NA, so integer columns don't become floats just because one value is missing.

Diagnose the pattern: compare missing rates across groups (df.groupby("employment")["income"].apply(lambda s: s.isna().mean())) and check correlations between missingness and other columns. Missing completely at random means dropping is mostly harmless; missing at random given other columns means you can impute using those columns; missing not at random (high earners skip the income question) can't be fixed from the data alone and needs domain knowledge or a sensitivity analysis.

Finding a hidden sentinel

df["age"].describe() shows min = 0 and many rows at exactly 0, and value_counts() shows 4,300 zeros. Ages of 0 aren't real, so df["age"] = df["age"].replace(0, np.nan) exposes the true missing rate.

Key takeaway: Count, hunt for sentinels, and compare missing rates across groups.

Choosing a fix without leaking or distorting

Drop rows when few are missing and the cause looks random (dropna(subset=["amount"])), and drop columns that are mostly empty and unimportant. Impute numeric columns with the median (robust to outliers) or a group median, categorical columns with the mode or an explicit "Unknown" category, and time series with forward fill or interpolation (ffill(), interpolate()), only where carrying values forward makes sense. Model-based imputers (IterativeImputer, KNNImputer) use other columns but are heavier and still need validation. Add a missing-indicator column when missingness could carry signal.

The most important rule for modelling: compute imputation values from the training set only and apply them to validation and test sets (use scikit-learn's SimpleImputer inside a Pipeline). Imputing the full dataset before splitting leaks test information into training. Afterwards, compare distributions before and after (describe(), histograms) to confirm you haven't flattened variance or created spikes at the fill value, and report the share of imputed values alongside any result.

Imputation inside a pipeline

pipe = Pipeline([("imp", SimpleImputer(strategy="median", add_indicator=True)), ("model", LogisticRegression())]); then pipe.fit(X_train, y_train) learns the medians from the training data only and reuses them on any new data.

Key takeaway: Median or group median plus an indicator, fitted on training data only.

How it works, step by step

Step 1 of 4
Detect

1. Count and convert

Measure missing percentages per column and convert sentinel values to real missing values.

df.isna().mean() · na_values=["N/A", -999]
Key numbers at this step
Includes
hidden sentinels

When to use it & trade-offs

What it is

Missing values appear as NaN, None, pd.NA or disguised sentinel values such as -999, "N/A", "unknown" or 0. Handling them means three steps: detect them (df.isna().sum()), understand why they're missing (random, related to other columns, or related to the missing value itself), and choose an action: drop rows or columns, fill (impute) with a rule or model, or keep missingness as information with an indicator column. The right choice depends on the reason, not on convenience.

Why it matters: Missing data is in nearly every real dataset, and the wrong fix quietly distorts results: filling with the mean shrinks variance, dropping rows removes a biased subset, and imputing before a train/test split leaks information from the test set. Interviewers often ask how you'd treat missing values and what could go wrong, expecting a reasoned answer rather than "use the mean".

When to reach for it

  • Median imputation plus an indicator for skewed numeric columns
  • Group-wise imputation when missingness varies by segment
  • Forward fill or interpolation for ordered time series

When to avoid or be careful

  • Imputing before the train/test split
  • Filling with the mean on skewed data
  • Treating 0 or -999 as real values

Ways to handle missing values

Drop rows or columns
Best for: A small share of values missing at random

Strengths: Simple; no invented data.

Watch out: Loses data and can bias the sample.

Simple imputation (median / mode / constant)
Best for: Baselines and tree or linear models

Strengths: Easy, fast, stable.

Watch out: Shrinks variance; ignores relationships between columns.

Model-based imputation + indicators
Best for: Missingness that depends on other columns or carries signal

Strengths: Uses more information; indicators keep the signal.

Watch out: More complex; must be validated and fitted without leakage.

Interview signals & numbers to know

When this topic comes up

  • “How would you handle missing data?”
  • “Why not just drop the rows?”
  • “What could go wrong with mean imputation?”
  • Data leakage
  • MCAR / MAR / MNAR

Benchmarks & rules of thumb

median -
robust default for numeric imputation
31% vs 6% -
missing rates by group in the example
train only -
where imputation values are learned

Common mistakes & follow-ups

Common interview mistakes

  • Computing the column mean on the full dataset before splitting, leaking test information.
  • Leaving 999 as a valid age and letting it drag the average up.
  • Dropping all rows with any missing value from a wide table and discarding most of the data.

Likely interviewer follow-ups

  • What are MCAR, MAR and MNAR?
  • When is it reasonable to drop rows?
  • How do you avoid leakage when imputing?
Interview tip: Open with "first I ask why it's missing". Then give the fix and the leakage caveat. That ordering signals real experience.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Handling Missing Values with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Indexing, Slicing & Filtering
Next topic
Duplicate Removal & Outlier Detection