Mean Imputation of Numeric Columns in a pandas DataFrame
SQL & DataModel answerLast updated
Replace NaNs in numeric DataFrame columns with column means, then extend it to in-place updates, per-group means and all-NaN columns, with non-numeric columns left alone.
You have a pandas DataFrame df in which several numeric columns contain NaN values. It may also hold text, categorical or datetime columns.
Write a compact pandas expression that replaces the missing entries in every numeric column with the mean of that column. All non-numeric columns must come out exactly as they went in, including any missing values they contain.
Then explain how you would adapt the solution to each of these requirements:
- In-place update. Modify
dfitself instead of producing a new frame. Say whether this is a good idea. - Per-group means. Fill each missing value with the mean of its own group, defined by a key column such as
'group', instead of the overall mean. - All-NaN columns. Leave any column that has no observed values untouched.
Discuss the edge cases you would check, such as the key column being numeric, a group with no observed values, or nullable integer dtypes.
Hints
Hint 1
`DataFrame.fillna` accepts a Series as its fill value. Think about how it lines that Series up with the DataFrame's columns, and what happens to columns that do not appear in it.
Hint 2
For grouped imputation you need a result with one value per original row, not one row per group. Look at `groupby(...).transform(...)` rather than `agg`.
Hint 3
The mean of a column with no observed values is itself NaN. Ask what filling NaN with NaN does, and what you should fall back to when a group has no data for a column.
Hint 4
Exclude the grouping key from the columns being filled, and check how recent pandas versions treat `mean()` on frames that contain text columns.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Compute one mean per numeric column, then hand that Series to fillna:
df = df.fillna(df.mean(numeric_only=True))
When fillna receives a Series, it matches the Series index against the DataFrame's column labels. Each column is filled using the value stored under its own name. A column whose name is missing from the Series (strings, categoricals, datetimes) has nothing to fill with, so it passes through unchanged. This satisfies the "leave non-numeric columns alone" rule with no explicit column selection and no loop.
Why it is correct:
mean()skips NaNs by default, so each mean uses only the observed values. This is the standard definition of mean imputation.- Alignment is by label, so column order is irrelevant and one column can never receive another's mean.
numeric_only=Trueis needed. Recent pandas versions raise aTypeErrorwhenmean()meets an object column, rather than silently dropping it.
(1) In-place update
df.fillna(df.mean(numeric_only=True), inplace=True)
The means are computed before anything is mutated, so there is no read/write conflict. My honest view is that inplace=True is rarely worth it:
- It usually does not save memory or time, because pandas often builds new arrays internally anyway.
- The pandas maintainers discourage it, and reassignment (
df = df.fillna(...)) is the idiomatic form. - Avoid the chained variant
df['a'].fillna(m, inplace=True). Under Copy-on-Write semantics it changes a temporary object and leavesdfuntouched. When targeting specific columns, assign back explicitly:df[cols] = df[cols].fillna(...).
(2) Per-group means
Use groupby(...).transform('mean'). It returns a frame with the same index as the original, where each row holds the mean of its group. That frame can go straight into fillna, which aligns it cell by cell:
num_cols = df.select_dtypes('number').columns.drop('group', errors='ignore')
df[num_cols] = df[num_cols].fillna(
df.groupby('group')[num_cols].transform('mean')
)
Points that distinguish a careful answer:
- Exclude the key. If
groupis numeric, averaging it is meaningless. transform, notagg.aggreturns one row per group, which would need a merge back.transformbroadcasts to the original rows.- Groups with no observed values. If every entry of a column within a group is NaN, the group mean is NaN and the cell stays empty. A sensible fallback chain is group mean first, then global mean.
- NaN keys.
groupbydrops rows with a NaN key by default, so those rows get NaN fromtransform. Either passdropna=Falseto treat NaN as its own group, or let the global-mean fallback cover them.
(3) Skipping all-NaN columns
The mean of a column with no observations is NaN, and filling NaN with NaN changes nothing, so the basic one-liner already leaves such columns as they were. To make the intent explicit, drop the NaN means first:
means = df.mean(numeric_only=True).dropna()
df = df.fillna(means)
If the requirement were instead to remove those columns, that is a different operation: df.dropna(axis=1, how='all'). Clarify which one is wanted.
Complete function
import pandas as pd
def fill_numeric_means(df: pd.DataFrame,
group_col: str | None = None,
inplace: bool = False) -> pd.DataFrame | None:
target = df if inplace else df.copy()
num_cols = target.select_dtypes('number').columns
if group_col is not None:
num_cols = num_cols.drop(group_col, errors='ignore')
# Global means; all-NaN columns give NaN and are dropped (skipped).
global_means = target[num_cols].mean().dropna()
cols = global_means.index
if len(cols) > 0:
filled = target[cols]
if group_col is not None:
group_means = (target.groupby(group_col, dropna=False)[cols]
.transform('mean'))
filled = filled.fillna(group_means)
# Fallback handles all-NaN groups and the ungrouped case.
target[cols] = filled.fillna(global_means)
return None if inplace else target
Worked example
df = pd.DataFrame({
'group': ['a', 'a', 'b', 'b', 'b'],
'score': [10, None, 20, None, 30],
'bonus': [None, None, None, 5, 7],
'empty': [None] * 5,
'label': ['u', None, 'w', 'x', 'y'],
})
- Global fill:
scoreNaNs become 20 (60 / 3),bonusNaNs become 6,emptystays all NaN, andlabelkeeps its NaN. - Grouped fill: row 1
scorebecomes 10 (groupa) and row 3scorebecomes 25 (groupb). Groupahas nobonusvalues, so rows 0 and 1 fall back to the global 6. Row 2bonusbecomes 6, the mean of groupb's 5 and 7.
Complexity
With n rows and m numeric columns:
| Variant | Time | Extra space |
|---|---|---|
| Global fill | O(n·m) | O(m) for the means, plus a new frame unless replaced in place |
| Grouped fill | O(n·m) with hash-based grouping | O(n·m) for the transform output, plus O(g·m) for group statistics |
Edge cases and pitfalls
- Integer columns containing NaN are stored as
float64, so a fractional mean fits. - Nullable
Int64columns may reject a non-integer fill. Cast toFloat64or round, depending on the meaning of the data. - Booleans count as numeric for
mean(numeric_only=True)but not forselect_dtypes('number'). Choose one definition and apply it consistently. - Empty frame or no numeric columns: the means Series is empty and
fillnadoes nothing, which is the right result. - Looping over columns or using
applyper column works but is slower and more verbose. The aligned Series is the idiomatic form. - Data leakage in ML work: compute means on the training split only, then apply those stored values to validation and test data. Computing them on the full dataset leaks information.
- Statistical caveat: mean imputation shrinks variance and can distort correlations. For heavily missing or skewed columns, consider the median, a model-based imputer, or adding a missingness indicator column.