Python · easy

How do you handle missing values in a pandas DataFrame?

Asked in Data Analyst interviews, in the Python round.

Short answer

fillna (mean/median/mode/forward-fill), dropna, or model-based imputation depending on context.

How to answer it

First find out why they are missing; the fix follows from the reason.

missing = df.isna().mean().sort_values(ascending=False)   # share missing per column, first
df["discount"] = df["discount"].fillna(0)
df["income"]   = df["income"].fillna(df["income"].median())
df["price"]    = df.sort_values("ts").groupby("sku")["price"].ffill()
df = df.dropna(subset=["user_id"])                          # a row with no key is not a row

For a model, add a "was missing" indicator column before imputing: missingness is often predictive, and imputation erases it. And compute the fill value on the training set only, then apply it to validation and test, or you have leaked.

Related questions

Practice this for real