Back to Practice
#0040

Fill Missing Values By Group Median

MediumPandas22 min15 XP

Problem

Given a DataFrame with city and income columns, fill missing income values with the median income of that same city.

Why This Matters

Real datasets often have missing values, and group-aware imputation is more realistic than one global fill value.

Function Signature

def fill_income_by_city_median(df):

Examples

Example 1
Inputcity A incomes [100, missing, 300], city B incomes [50, missing, 70]
Outputcity A missing becomes 200, city B missing becomes 60

Each missing value uses the median from its own city, not the whole dataset.

Constraints

  • Return a new DataFrame.
  • Keep the original row order.
  • Do not fill a city if all its incomes are missing.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 4 hidden categories
Two city medians
Inputcity A and B incomes with missing values
Expectedmissing values filled by city median

transform returns one median value aligned to each original row.

Hidden Test Categories
City with no missing valuesCity with all missing valuesOdd and even group sizesOriginal DataFrame mutation check