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.

Sample data

These tables are loaded into an in-browser engine on this page, so you can run your own answer against them. No account needed.

survey

respondent_idageincomecity
13472000Austin
2NULL58000Denver
341NULLAustin
42963000NULL
5NULLNULLBoston
65291000Denver
73867000Boston

How to answer it

Definition

There is no single right answer. The right handling depends on why the value is missing, and saying that first is most of what is being tested.

Why it is missing

Syntax

df.isna().sum()                        # where and how much
df.dropna(subset=["revenue"])          # drop rows missing a specific column
df["x"] = df["x"].fillna(df["x"].median())
df["x"] = df["x"].ffill()              # ordered data: carry the last value
df["x_missing"] = df["x"].isna().astype(int)   # keep the fact of absence

Example

print(df.isna().mean().sort_values(ascending=False).head())

df["signup_source"] = df["signup_source"].fillna("unknown")
df["age_missing"] = df["age"].isna().astype(int)
df["age"] = df["age"].fillna(df["age"].median())

Output

age              0.184
signup_source    0.061
revenue          0.000
dtype: float64

Key points

FAQ

The 30-second answer

The first thing I would say is that it depends on why the value is missing, so I would start with isna per column to see how much is gone and where.
If it is missing at random and rare I might drop those rows. For a numeric column I usually impute with the median rather than the mean, because the mean is already pulled around by the skew that made the column messy. For ordered data I would forward fill, but only after sorting.
The part people skip is that the absence is often signal itself, so I add a boolean column recording that the value was missing before I fill it. And I fit the imputation on the training set only, because using the whole dataset's median leaks the test set into training.

In the interview

Practice this for real