← All Python interview questions
Fill missing product ratings the defensible way
EasyPandas — CleaningAmazonNykaa
A ratings export has gaps. The analytics lead wants missing ratings filled with the median rating of that product's category, not a global constant.
Write fill_ratings(df) that returns a copy of the DataFrame with the rating column filled that way, rounded to 2 decimals. The original DataFrame must not change.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
import numpy as np
products = pd.DataFrame({
"sku": ["A1", "A2", "A3", "B1", "B2", "B3"],
"category": ["Grocery", "Grocery", "Grocery", "Fashion", "Fashion", "Fashion"],
"rating": [4.5, np.nan, 3.5, 2.0, np.nan, 4.0],
})- Step 1: `df.copy()` keeps the caller's DataFrame untouched — mutating an input is the fastest way to create a bug nobody can reproduce.
- Step 2: `groupby('category')['rating'].transform('median')` returns a Series aligned to the original rows, so every row already knows its category median.
- Step 3: `fillna(medians)` replaces only the gaps; existing ratings are left exactly as they were.
- Step 4: `median` is chosen over `mean` because ratings are skewed by a handful of 1-star reviews.
def fill_ratings(df):
out = df.copy()
medians = out.groupby("category")["rating"].transform("median")
out["rating"] = out["rating"].fillna(medians).round(2)
return outLearn the concept first
Stuck on Pandas — Cleaning? These free Python lessons teach it step by step.
More Pandas — Cleaning questions
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program