818. Fill missing values with the group mean in pandas
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.
def 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.
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)