Sub topic 9
Filling within groups
This chapter assumes you know fillna with constants and statistics, and the basics of groupby. A single overall mean can be a poor fill value when groups differ a lot. Filling within groups uses a value computed from each row's own group.
Why a global fill can mislead
Suppose team A scores around 10 and team B around 20. Filling every gap with the overall mean of 15 pulls both teams toward the middle. A group-wise fill keeps each team's level.
Fill with a group statistic using transform
groupby(...).mean() returns one row per group. fillna needs one value per original row, so that result cannot be used directly. transform fixes this. It computes the statistic per group, then returns a Series with the same index as the original data.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"team": ["a", "a", "b", "b"],
"score": [10.0, np.nan, 20.0, np.nan],
})
df["score"] = df["score"].fillna(df.groupby("team")["score"].transform("mean"))
print(df)The output fills row 1 with 10.0 (team a's mean) and row 3 with 20.0 (team b's mean). fillna accepts a Series and matches it to the data by index label, so the aligned output of transform works as a fill source.
Groups that are entirely missing
If every value in a group is missing, the group mean is also NaN, and fillna leaves those rows empty. Chain a second fillna as a fallback:
import numpy as np
import pandas as pd
df = pd.DataFrame({
"team": ["a", "a", "b", "b", "c"],
"score": [10.0, np.nan, 20.0, np.nan, np.nan],
})
group_mean = df.groupby("team")["score"].transform("mean")
df["score"] = df["score"].fillna(group_mean).fillna(df["score"].median())
print(df)Team c has no observed scores, so its row gets the overall median of 15.0. Both fills read the original column, because the assignment happens only after the whole expression is evaluated.
Forward fill within groups
Forward fill on a whole column can carry a value from one group into the next. Calling ffill on the grouped column restricts the fill to each group:
import numpy as np
import pandas as pd
df = pd.DataFrame({
"team": ["a", "b", "a", "b"],
"score": [1.0, 5.0, np.nan, np.nan],
})
print(df["score"].ffill().tolist())
print(df.groupby("team")["score"].ffill().tolist())The ungrouped call gives [1.0, 5.0, 5.0, 5.0], so team a's gap receives team b's value. The grouped call gives [1.0, 5.0, 1.0, 5.0], which is correct. bfill behaves the same way. Sort the data by time inside each group first, because both methods fill by row order.
Common errors
- Using an aggregated result directly.
df.groupby("team")["score"].mean()has the team names as its index, so it does not line up with the row labels. Usetransform. - Forgetting the assignment. Like other fill methods, these calls return a new object. Assign the result back to the column.
- Missing group keys. Rows whose
teamisNaNdo not belong to any group by default, so they getNaNfromtransformand stay unfilled. Handle those keys first, or passdropna=Falsetogroupby. - Tiny groups. A mean based on one or two observations is unstable. Check group sizes with
df.groupby("team")["score"].count()before trusting the fill.
Exercise
A DataFrame has columns "dept" and "salary". Some salaries are NaN. Write one line that fills each missing salary with the median salary of its own department, assigning the result back to the column.
Show answer
df["salary"] = df["salary"].fillna(df.groupby("dept")["salary"].transform("median"))
Exercise
You run df.groupby("team")["score"].ffill() on rows ordered a, b, a, b. The first row of team b has a missing score. What does that row contain afterwards, and why?
Show answer
It stays NaN. Forward fill only copies values from earlier rows of the same group, and team b has no earlier observed value. The value from team a is not used, because the fill is restricted to each group.