BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / pandas18 of 18 in topic

818. Fill missing values with the group mean in pandas

Easypandas

Why it matters Feature pipelines for tabular ML and dashboards on LLM usage logs both need group-aware imputation.

Filling a missing value with the global mean ignores obvious structure: a missing latency for a big model should borrow from that model's other requests, not the overall average.

Write fill_by_group(df, group_col, value_col). Return a new DataFrame where missing values in value_col are replaced by the mean of value_col within the same group_col value (pandas mean skips NaN). If a whole group is missing, fill it with the overall mean of value_col. Keep the original row order and index, and do not modify df.

Functiondef fill_by_group(df, group_col, value_col)

Example 1

Input: fill_by_group(pd.DataFrame({'g': ['x', 'x', 'y'], 'v': [1.0, None, 5.0]}), 'g', 'v')['v'].tolist()

Output: [1.0, 1.0, 5.0]

Example 2

Input: fill_by_group(pd.DataFrame({'g': ['a', 'b', 'b'], 'v': [None, 2.0, 6.0]}), 'g', 'v')['v'].tolist()

Output: [4.0, 2.0, 6.0]

Example 3

Input: fill_by_group(pd.DataFrame({'g': [1, 2, 1], 'v': [None, 4.0, 2.0]}, index=[7, 8, 9]), 'g', 'v').index.tolist()

Output: [7, 8, 9]

Constraints

  • Python 3 with pandas. Code runs in your browser.
  • Your code must pass all 5 tests to be accepted.
Hint 1

transform keeps the original shape and index, unlike agg.

Hint 2

Chain a second fillna for groups with no values at all.

Common mistakes
  • Using groupby().mean(), which returns one row per group and does not align with the rows.
  • Changing df in place.
Understand the idea

groupby(...).transform('mean') returns a Series aligned to the original rows, with each row's group mean. fillna with that Series fills only the gaps. A second fillna with the global mean covers groups that are entirely missing.

Worked example

model a has [10, NaN] so the gap becomes 10; model c has only NaN, so it gets the overall mean (10 + 30 + 50) / 3 = 30.

fillna(groupby.transform('mean')).fillna(overall mean)
Topics
pandas
Similar questions
  • Summarise API calls per model with named groupby aggregationsEasy
  • Keep only the latest subscription record per userEasy
  • Melt a wide leaderboard into long rows and drop missing scoresEasy
  • Compare class balance across train, val and test with value_countsEasy
All pandas problems
Report
818 / 903
Python 3solution.pyPython idle
1
2
3
4
def fill_by_group(df, group_col, value_col):
# your code here
pass
​
fill_by_group(pd.DataFrame({'g': ['x', 'x', 'y'], 'v': [1.0, None, 5.0]}), 'g', 'v')['v'].tolist()

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS