Impute Missing Values by Group

medium
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 10. Everything before it counts as cleared.

Filling every missing value with the global mean ignores structure: a missing house price in London shouldn't be filled with the national average.

Implement impute(df, col, by, strategy="median"):

  • Fill missing values in col with the strategy ("median" or "mean") of the row's group (by is a column name or list of names).
  • If a whole group is missing, fall back to the global statistic.
  • Add a boolean column f"{col}_was_missing" so the model can still see which values were imputed.
  • Return a new DataFrame and don't modify the input.

Then implement missing_report(df): a DataFrame indexed by column name with n_missing and pct_missing (0–100, rounded to 1 decimal), sorted by n_missing descending, then column name, including only columns with missing values.

#pandas#missing-data#cleaning2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Impute Missing Values by Group · TechGradify