KatInterview

Mean Imputation of Numeric Columns in a pandas DataFrame

SQL & DataModel answer
MediumModel answerSQL & Datapandasmissing-dataimputation

Last 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:

  1. In-place update. Modify df itself instead of producing a new frame. Say whether this is a good idea.
  2. 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.
  3. 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.