Sub topic 9
Filling within groups
This chapter assumes you can already use fillna, isna, and groupby with a single aggregation such as mean. It also assumes you know how ffill and interpolate work on one Series. The goal is to apply those tools separately inside each group, so a value from one group never fills a gap in another.
Why a global fill can mislead
df["score"].fillna(df["score"].mean()) uses one number for every row. That is fine when the rows are alike. It is wrong when the data holds distinct populations, such as teams, sensors, stores, or regions.
Suppose team a scores around 12 and team b scores around 30. Filling a missing b score with the overall mean of 21 makes b look worse than it is. It also pulls a upward. The fix is to compute the statistic per group and use it only for rows in that group.
The groupby and transform pattern
groupby(...).transform(...) computes a statistic per group and returns a result with the same length and index as the original column. Each row gets the value for its own group. Because the shapes match, you can pass that result straight to fillna.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"team": ["a", "a", "a", "b", "b", "b"],
"score": [10.0, np.nan, 14.0, 20.0, np.nan, 40.0],
})
group_mean = df.groupby("team")["score"].transform("mean")
df["score"] = df["score"].fillna(group_mean)
print(df) team score
0 a 10.0
1 a 12.0
2 a 14.0
3 b 20.0
4 b 30.0
5 b 40.0The group means are 12 for a and 30 for b. The missing value in row 1 gets 12 and the one in row 4 gets 30. Rows that already had a value are untouched, because fillna only replaces missing cells. The mean skips NaN by default, so missing values do not distort the statistic.
Here is the data flow.
Why transform and not agg or apply
The choice of method decides whether the result can be used for filling.
| Method | Result shape | Usable directly in `fillna`? |
|---|---|---|
| `groupby(...).mean()` or `agg` | One row per group, indexed by group key | No. The index is the team, not the row. |
| `groupby(...).transform("mean")` | Same length and index as the input | Yes |
| `groupby(...).apply(func)` | Depends on what `func` returns | Only if `func` returns a same-indexed result |
If you call df["score"].fillna(df.groupby("team")["score"].mean()), pandas aligns on the index. The team labels a and b do not match the row labels 0 to 5, so nothing is filled and you get no error. Use transform whenever the filler must line up with the original rows.
Other statistics and a lambda form
Any named aggregation works as a string: "median", "min", "max", "first", "last". The median is a better choice when a group has outliers.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"store": ["n", "n", "n", "s", "s"],
"sales": [100.0, np.nan, 900.0, 50.0, np.nan],
})
df["sales"] = df["sales"].fillna(df.groupby("store")["sales"].transform("median"))
print(df)You can also write the fill inside the transform with a lambda, which is useful when the logic needs more than one step:
df["sales"] = df.groupby("store")["sales"].transform(lambda s: s.fillna(s.median()))Both forms give the same result. The string form is usually faster because pandas can use its compiled group code. The lambda runs Python once per group. Prefer the string form unless you need custom logic.
To group by several columns, pass a list: df.groupby(["region", "team"]). More keys make each group smaller, and small groups give noisy statistics. A mean built from one or two values is not much better than a guess.
Forward fill and interpolation inside groups
Forward fill carries the last known value down the column. On a stacked table with several entities, a global ffill copies a value from the end of one entity into the start of the next. Grouping prevents that.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"sensor": ["x", "x", "y", "y"],
"reading": [1.0, np.nan, np.nan, 5.0],
})
df["global_ffill"] = df["reading"].ffill()
df["group_ffill"] = df.groupby("sensor")["reading"].ffill()
print(df) sensor reading global_ffill group_ffill
0 x 1.0 1.0 1.0
1 x NaN 1.0 1.0
2 y NaN 1.0 NaN
3 y 5.0 5.0 5.0Row 2 belongs to sensor y, which has no earlier reading. The global fill gave it sensor x's value, which is a leak between entities. The grouped version leaves it missing, and that is the honest answer.
ffill, bfill, and fillna with a limit all work directly on a grouped column. To limit how far a value carries, use groupby("sensor")["reading"].ffill(limit=2).
For interpolation, wrap the call in transform:
import numpy as np
import pandas as pd
df = pd.DataFrame({
"id": ["a", "a", "a", "b", "b", "b"],
"v": [1.0, np.nan, 3.0, np.nan, 10.0, 30.0],
})
df["global"] = df["v"].interpolate()
df["grouped"] = df.groupby("id")["v"].transform(lambda s: s.interpolate())
print(df) id v global grouped
0 a 1.0 1.0 1.0
1 a NaN 2.0 2.0
2 a 3.0 3.0 3.0
3 b NaN 6.5 NaN
4 b 10.0 10.0 10.0
5 b 30.0 30.0 30.0Row 3 is the first row of group b. The global interpolation draws a line from group a's last value (3.0) to group b's first (10.0) and produces 6.5, which is a number that no measurement supports. The grouped version sees a leading gap, which interpolate does not fill by default, and leaves it missing.
The row order inside each group has to be meaningful. If the data is not already sorted by time or position, sort first with df.sort_values(["id", "date"]).
Groups that are entirely missing
If every value in a group is missing, the group mean is NaN. Filling with it changes nothing. Chain a second fillna as a fallback:
import numpy as np
import pandas as pd
df = pd.DataFrame({
"team": ["a", "a", "a", "b", "b", "c", "c"],
"score": [10.0, np.nan, 20.0, 30.0, np.nan, 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 score
0 a 10.0
1 a 15.0
2 a 20.0
3 b 30.0
4 b 30.0
5 c 20.0
6 c 20.0Team c has no data, so it falls back to the overall median of 20. The fallback value is computed from the original column, because the right-hand side is evaluated before the assignment. Whether such a fallback is reasonable is a modelling decision. Sometimes leaving team c missing is the better answer, and you can check for it afterwards with df["score"].isna().sum().
Rows whose group key is missing
By default groupby drops rows whose key is missing. For transform, those rows come back as NaN, so a fillna using that result leaves them unfilled.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", None, "Oslo", "Rome", None],
"age": [20.0, 30.0, np.nan, 40.0, np.nan],
})
default = df["age"].fillna(df.groupby("city")["age"].transform("mean"))
keep_keys = df["age"].fillna(df.groupby("city", dropna=False)["age"].transform("mean"))
print(pd.DataFrame({"default": default, "dropna_false": keep_keys})) default dropna_false
0 20.0 20.0
1 30.0 30.0
2 20.0 20.0
3 40.0 40.0
4 NaN 30.0With dropna=False, the rows with a missing city form their own group. Row 4 is filled with 30, the mean of the other rows that have no city. Decide whether that is sensible. Rows with an unknown city are not necessarily alike, so this is often a weak fill. Leaving them missing, or filling the city first, can be more defensible.
Common errors
- Using
.mean()instead of.transform("mean"). The result is indexed by group, sofillnaaligns on the wrong index and fills nothing. Check the result withisna().sum()after filling. - Filling before sorting. Grouped
ffillandinterpolatedepend on row order inside each group. - Assuming every group has a value. Groups with all values missing stay missing unless you add a fallback.
- Ignoring tiny groups. A mean from a single value copies that value to every other row in the group.
- Using
inplace=Trueon a selection. Assign the result back instead:df["score"] = .... - Leaking information. If the filled column feeds a model, compute group statistics from the training rows only.
Exercise
A DataFrame has columns "dept" and "salary". Some salaries are missing. Write one line that fills each missing salary with the median salary of that employee's department, and explain why df.groupby("dept")["salary"].median() cannot be passed to fillna directly.
Show answer
Use df["salary"] = df["salary"].fillna(df.groupby("dept")["salary"].transform("median")). The plain median() returns one value per department, indexed by department name. fillna aligns on the index, so the department names do not match the row labels and nothing is filled. transform("median") returns a Series with one value per original row, indexed like the DataFrame, so each row receives the median of its own department.
Exercise
A table stacks daily readings for two sensors, sorted by sensor and date. A plain ffill fills the first missing reading of the second sensor with the last value of the first sensor. How do you prevent this, and what happens to a missing reading that comes before any real reading for its sensor?
Show answer
Group by sensor before filling: df["reading"] = df.groupby("sensor")["reading"].ffill(). The fill then restarts for each sensor. A missing reading that comes before any real reading for its sensor has nothing to carry forward, so it stays NaN. You can then decide whether to use bfill, a fallback constant, or leave it missing.