Column and Group Mean Imputation

Medium · Data Manipulation (SQL/Python) · Software Engineer · Technical Screen

Problem Statement

Tabular datasets frequently contain missing entries scattered across both numeric and non-numeric columns. In pandas, analysts impute missing numbers using concise column-level or group-level mean expressions; here, we model a column-oriented DataFrame in pure Python as Table = Dict[str, List[Any]], where each key maps a column name to an equal-length list of row values.

Follow these data conventions across every operation:

  • A cell is missing when it is None or an IEEE-754 floating-point NaN (float("nan")).
  • A column is numeric when every non-missing cell is an int or float, excluding bool (True and False are treated as non-numeric).
  • Arithmetic means are computed strictly over observed (non-missing) entries as float values.

Implement three functions (and be ready to explain their concise pandas counterparts):

  1. fill_with_column_means(table: Table) -> Table: Return a new table (without mutating table or its column lists) in which every missing cell of each numeric column is replaced by that column's observed mean. Copy non-numeric columns and columns that have zero observed entries (all missing or empty) unchanged.
  2. fill_with_column_means_inplace(table: Table) -> None: Perform the exact same column-mean replacement by mutating table's lists directly in place and returning None.
  3. fill_with_group_means(table: Table, key: str) -> Table: Return a new table (without mutating table) where each missing cell in a numeric column other than key is filled with the mean of observed values in that column among rows sharing the same non-missing table[key] value. Never fill the grouping column key itself. If a row's key entry is missing, or if its group has zero observed values in that column, fall back to the overall column mean; if the entire column has zero observed values, leave the cell missing.

Examples

Example 1

Input:

nan = float("nan")
table = {
    "team": ["east", "east", "west", "west", "west"],
    "score": [2.0, nan, 8.0, nan, 14.0],
    "bonus": [20, None, 40, 60, None],
    "label": ["p1", "p2", None, "p4", "p5"],
    "empty": [nan, nan, nan, nan, nan],
}
fill_with_column_means(table)

Output:

{
    "team": ["east", "east", "west", "west", "west"],
    "score": [2.0, 8.0, 8.0, 8.0, 14.0],
    "bonus": [20, 40.0, 40, 60, 40.0],
    "label": ["p1", "p2", None, "p4", "p5"],
    "empty": [nan, nan, nan, nan, nan],
}

Walk-through: Observed entries in "score" (2.0, 8.0, 14.0) average to 8.0, and observed entries in "bonus" (20, 40, 60) average to 40.0. "team" and "label" contain strings so their cells stay untouched, and "empty" has zero observed numbers so its nan cells are skipped. Calling fill_with_column_means_inplace(table) mutates table to this exact state and returns None.

Example 2

Input:

# Using the same 5-row `table` from Example 1:
fill_with_group_means(table, "team")

Output:

{
    "team": ["east", "east", "west", "west", "west"],
    "score": [2.0, 2.0, 8.0, 11.0, 14.0],
    "bonus": [20, 20.0, 40, 60, 50.0],
    "label": ["p1", "p2", None, "p4", "p5"],
    "empty": [nan, nan, nan, nan, nan],
}

Walk-through: Within "east", observed "score" is [2.0] (mean 2.0) and "bonus" is [20] (mean 20.0), filling row 1. Within "west", observed "score" is [8.0, 14.0] (mean 11.0) and "bonus" is [40, 60] (mean 50.0), filling rows 3 and 4.

Example 3

Input:

nan = float("nan")
table = {
    "dept": ["eng", "eng", "sales", "ops", None],
    "latency": [10.0, nan, 50.0, nan, nan],
}
fill_with_group_means(table, "dept")

Output:

{
    "dept": ["eng", "eng", "sales", "ops", None],
    "latency": [10.0, 10.0, 50.0, 30.0, 30.0],
}

Walk-through: Row 1 belongs to "eng", whose observed "latency" mean is 10.0. Row 3 belongs to "ops" (zero observed "latency" entries) and row 4 has a missing "dept" key (None), so both fall back to the overall "latency" mean (10.0 + 50.0) / 2 = 30.0.

Constraints

  • All column lists inside table have equal length 0 <= n <= 10^5, and 0 <= len(table) <= 200.
  • For fill_with_group_means(table, key), key is guaranteed to be an existing column key in table, and observed group keys are hashable.
  • Non-in-place functions (fill_with_column_means and fill_with_group_means) must never mutate table or its inner lists.
  • Aim for O(n * c) time across n rows and c columns rather than rescanning a column on every missing cell.

Step-by-step walkthrough

  1. Understand the goal and set up a 5-row sample table

    We have a column-oriented table containing missing cells (NaN or None) across several columns. Our goal is to replace missing entries in numeric columns with their arithmetic mean while leaving text/boolean columns and zero-observation (all-NaN) columns unchanged — across three practical modes:

    • Global column means (fill_with_column_means): Return a new table with missing numbers filled by each column's overall mean, leaving the caller's input untouched.
    • In-place mutation (fill_with_column_means_inplace): Update the existing table's column lists directly and return None.
    • Per-group means (fill_with_group_means): Fill each missing number using the mean of its own group (keyed by a column such as "team"), falling back to the overall column mean whenever a group has zero observed values or the row's key is missing.

    In an interview, you will write concise pandas expressions first. Because our test runner uses the Python standard library without pandas, we show both the exact pandas idioms and their pure-Python counterparts on Table = Dict[str, List[Any]].

    Here is the 5-row sample table from Examples 1 and 2 that we will trace throughout:

    row   team     score   bonus   label   empty (all missing)
     0    east      2.0     20      p1     NaN
     1    east      NaN    None     p2     NaN
     2    west      8.0     40     None    NaN
     3    west      NaN     60      p4     NaN
     4    west     14.0    None     p5     NaN
    
  2. Write the concise pandas one-liner

    In pandas, replacing missing entries in numeric columns with each column's mean takes a single readable expression:

    df = df.fillna(df.mean(numeric_only=True))
    

    Why each piece of that expression matters:

    • df.mean(numeric_only=True) scans only numeric columns, ignores NaNs automatically (skipna=True by default), and returns a Series indexed by column name: score -> 8.0, bonus -> 40.0, empty -> NaN. Passing numeric_only=True is essential — since pandas 2.0, omitting it raises a TypeError whenever the DataFrame contains string columns like "team" or "label".
    • df.fillna(series) matches the Series index labels against df's column names, filling score with 8.0 and bonus with 40.0 while ignoring "team" and "label" completely.

    If your DataFrame also contains nullable boolean columns (True / False / <NA>), selecting strictly number-typed columns with select_dtypes(include="number") is even safer because mean(numeric_only=True) treats booleans as 0/1 numbers whereas select_dtypes(include="number") excludes booleans cleanly:

    num_cols = df.select_dtypes(include="number").columns
    df[num_cols] = df[num_cols].fillna(df[num_cols].mean())
    
  3. Build the pure-Python helpers: missing check, numeric check, and mean

    To implement the exact same rules on Table = Dict[str, List[Any]], we start with three small helper functions that avoid two classic Python traps:

    1. NaN != NaN: In IEEE-754 floating-point math, float("nan") == float("nan") evaluates to False! Always detect NaN using math.isnan(value) after checking isinstance(value, float).
    2. bool subclasses int: In Python, isinstance(True, int) is True (True == 1 and False == 0). So is_numeric_column must reject isinstance(value, bool) before accepting (int, float), matching select_dtypes(include="number").
    3. Zero observed values: If every entry in a column is missing, count == 0 — returning None avoids ZeroDivisionError (mirroring how pandas returns NaN).
    def is_missing(value: Any) -> bool:
        """Return True when value is None or IEEE-754 float NaN (pandas missing markers)."""
        # NaN != NaN in floating point, so we must check math.isnan rather than `== float("nan")`.
        return value is None or (isinstance(value, float) and math.isnan(value))
    
    
    def is_numeric_column(values: List[Any]) -> bool:
        """Return True if every non-missing entry is an int or float (matching select_dtypes('number'))."""
        for value in values:
            if is_missing(value):
                continue
            # Check `bool` first because `bool` subclasses `int` in Python (`isinstance(True, int)` is True).
            if isinstance(value, bool) or not isinstance(value, (int, float)):
                return False
        return True
    
    
    def column_mean(values: List[Any]) -> Optional[float]:
        """Return the arithmetic mean of non-missing entries, or None if the column has none."""
        total = 0.0
        count = 0
        for value in values:
            if not is_missing(value):
                total += float(value)
                count += 1
        # An empty or all-missing column has count == 0; return None instead of dividing by zero.
        if count == 0:
            return None
        return total / count
    
  4. Fill column means in-place vs. returning a new copy

    In pandas, there are two clean ways to update df directly in place:

    # Option 1: call fillna directly on df itself with inplace=True
    df.fillna(df.mean(numeric_only=True), inplace=True)
    
    # Option 2: assign filled numeric columns back into df
    num_cols = df.select_dtypes(include="number").columns
    df[num_cols] = df[num_cols].fillna(df[num_cols].mean())
    

    Watch out for two infamous inplace=True pitfalls in pandas:

    • Never call .fillna(..., inplace=True) on a column slice like df[num_cols].fillna(..., inplace=True) or df["score"].fillna(m, inplace=True). Indexing df[num_cols] builds a separate copy, and under pandas Copy-on-Write even df["score"] behaves like a copy — so mutating that temporary slice leaves df itself full of NaNs!
    • Never combine assignment with inplace=True (df = df.fillna(..., inplace=True)), because in pandas 1.x/2.x inplace=True returns None and wipes out your variable.

    In our pure-Python implementation, fill_with_column_means_inplace mutates each eligible column list directly and returns None, while fill_with_column_means shallow-copies each column list first (list(values)) and delegates to fill_with_column_means_inplace so there is zero duplicated logic:

    def fill_with_column_means_inplace(table: Table) -> None:
        """Same result as fill_with_column_means, but change `table` itself and return None."""
        # Mutate each eligible numeric column list in place; skip text/bool and all-missing columns.
        for values in table.values():
            if not is_numeric_column(values):
                continue
            mean_val = column_mean(values)
            if mean_val is None:
                continue  # Skip columns that have zero observed numeric values
            for row_idx in range(len(values)):
                if is_missing(values[row_idx]):
                    values[row_idx] = mean_val
    
    
    def fill_with_column_means(table: Table) -> Table:
        """Return a new table where each missing value in a numeric column is that column's mean.
    
        The mean ignores missing values. Non-numeric columns and columns with no observed
        value (all missing) are copied unchanged. The input table must not be modified.
        pandas: df.fillna(df.mean(numeric_only=True))
        """
        # Shallow-copy every column list first so the caller's input lists are never mutated.
        result: Table = {}
        for col_name, values in table.items():
            result[col_name] = list(values)
        fill_with_column_means_inplace(result)
        return result
    
  5. Fill with per-group means and fall back when a group is empty

    To fill each missing cell with its own group's mean, df.groupby("team")[num_cols].mean() has the wrong shape — it collapses 5 rows down to 2 summary rows ("east" and "west"). Instead, pandas provides .transform("mean"), which broadcasts each group's mean back into a DataFrame of the exact same 5-row shape and index as df:

    num_cols = df.select_dtypes(include="number").columns.drop("team", errors="ignore")
    group_means_df = df.groupby("team")[num_cols].transform("mean")
    df[num_cols] = df[num_cols].fillna(group_means_df).fillna(df[num_cols].mean())
    

    Notice three edge cases handled cleanly by those three lines:

    1. Never fill the grouping column itself: .drop("team", errors="ignore") protects the key column even when group IDs are integers (1, 2, ...).
    2. Group with zero observed values: As in Example 3 (dept = "ops"), transform("mean") puts NaN for "ops", and the chained .fillna(df[num_cols].mean()) seamlessly falls back to the overall column mean!
    3. Missing group key (None / NaN): By default groupby skips NaN keys, so transform("mean") outputs NaN on that row, and the second .fillna(...) fills it with the overall column mean.

    In pure Python, group_means accumulates totals and counts per non-missing key in a single O(n) pass, and fill_with_group_means checks per_group first before falling back to overall_mean:

    def group_means(keys: List[Any], values: List[Any]) -> Dict[Any, float]:
        """Compute observed mean per non-missing group key (twin of df.groupby(key)[col].mean())."""
        # totals: {group_key: sum_of_observed_values}, counts: {group_key: num_observed_values}
        totals: Dict[Any, float] = {}
        counts: Dict[Any, int] = {}
        for group_key, value in zip(keys, values):
            # pandas groupby drops NaN/None group keys by default, and mean skips missing values.
            if is_missing(group_key) or is_missing(value):
                continue
            totals[group_key] = totals.get(group_key, 0.0) + float(value)
            counts[group_key] = counts.get(group_key, 0) + 1
    
        means: Dict[Any, float] = {}
        for group_key, total in totals.items():
            means[group_key] = total / counts[group_key]
        return means
    
    
    def fill_with_group_means(table: Table, key: str) -> Table:
        """Return a new table where each missing numeric value is the mean of its row's group.
    
        Groups are the distinct values of column `key`; the key column itself is never filled.
        If the row's group has no observed value in that column, or the row's key is missing,
        use the overall column mean instead. If the column has no observed value at all,
        leave the value missing. The input table must not be modified.
        """
        keys = table[key]
        result: Table = {}
    
        for col_name, values in table.items():
            filled = list(values)
            result[col_name] = filled
    
            # Never impute the grouping key column itself or non-numeric columns.
            if col_name == key or not is_numeric_column(values):
                continue
    
            # Precompute per-group means (dict {group_key: mean}) and global fallback mean in O(n).
            per_group = group_means(keys, values)
            overall_mean = column_mean(values)
    
            for row_idx in range(len(filled)):
                if not is_missing(filled[row_idx]):
                    continue
                row_key = keys[row_idx]
                # Use the row's group mean when available; otherwise fall back to overall column mean.
                if not is_missing(row_key) and row_key in per_group:
                    filled[row_idx] = per_group[row_key]
                elif overall_mean is not None:
                    filled[row_idx] = overall_mean
    
        return result
    
  6. Skip zero-observation columns explicitly

    In df.fillna(df.mean(numeric_only=True)), an all-NaN column like empty stays NaN because its mean is NaN, and replacing NaN with NaN is a no-op. Making that skip explicit with .dropna() on the means Series is cleaner and faster because pandas never even visits all-NaN columns during fillna:

    valid_means = df.mean(numeric_only=True).dropna()  # drops 'empty' since its mean is NaN
    df = df.fillna(valid_means)
    

    (If a caller wanted to delete all-NaN columns rather than skip them, that would be df.dropna(axis=1, how="all"); skipping keeps those columns intact.) In our Python code, if mean_val is None: continue and elif overall_mean is not None: implement that exact explicit skip.

  7. Trace Examples 1, 2, and 3 step by step

    Let's compare fill_with_column_means and fill_with_group_means side by side on our 5-row sample table:

    Input:
      team:   ["east", "east", "west", "west", "west"]
      score:  [2.0,    NaN,    8.0,    NaN,    14.0  ]
      bonus:  [20,     None,   40,     60,     None  ]
      label:  ["p1",   "p2",   None,   "p4",   "p5"  ]   (non-numeric -> untouched)
      empty:  [NaN,    NaN,    NaN,    NaN,    NaN   ]   (all-missing -> skipped)
    
    Example 1 — Global column means:
      mean(score) = (2.0 + 8.0 + 14.0) / 3 = 8.0   ->  score becomes [2.0, 8.0, 8.0, 8.0, 14.0]
      mean(bonus) = (20 + 40 + 60) / 3     = 40.0  ->  bonus becomes [20,  40.0, 40, 60,  40.0]
    
    Example 2 — Per-group means (key = "team"):
      score in "east": observed [2.0]       -> mean 2.0  |  in "west": observed [8.0, 14.0] -> mean 11.0
        => score becomes [2.0, 2.0, 8.0, 11.0, 14.0]
      bonus in "east": observed [20]        -> mean 20.0 |  in "west": observed [40, 60]    -> mean 50.0
        => bonus becomes [20, 20.0, 40, 60, 50.0]
    

    Look at row 1 (team = "east"): global imputation fills score[1] with 8.0 (pulled upward by "west"'s larger numbers), whereas group imputation fills score[1] with 2.0, preserving "east"'s actual scale! Meanwhile, in Example 3 (dept = ["eng", "eng", "sales", "ops", None], latency = [10.0, NaN, 50.0, NaN, NaN]), "eng" fills row 1 with its group mean 10.0, while "ops" (zero observed values) and None (missing key) fall back cleanly to overall_mean = 30.0.

  8. Put it all together

    Here is the complete solution.py:

    from typing import Any, Dict, List, Optional
    import math
    
    # Pure-Python column dictionary modeling a tabular DataFrame:
    #   {"team": ["east", "east", "west"], "score": [2.0, nan, 8.0], "label": ["p1", None, "p3"]}
    # A cell is missing if it is None or a float NaN. A column is numeric if every
    # non-missing cell is an int or a float (bool does not count).
    Table = Dict[str, List[Any]]
    
    
    def is_missing(value: Any) -> bool:
        """Return True when value is None or IEEE-754 float NaN (pandas missing markers)."""
        # NaN != NaN in floating point, so we must check math.isnan rather than `== float("nan")`.
        return value is None or (isinstance(value, float) and math.isnan(value))
    
    
    def is_numeric_column(values: List[Any]) -> bool:
        """Return True if every non-missing entry is an int or float (matching select_dtypes('number'))."""
        for value in values:
            if is_missing(value):
                continue
            # Check `bool` first because `bool` subclasses `int` in Python (`isinstance(True, int)` is True).
            if isinstance(value, bool) or not isinstance(value, (int, float)):
                return False
        return True
    
    
    def column_mean(values: List[Any]) -> Optional[float]:
        """Return the arithmetic mean of non-missing entries, or None if the column has none."""
        total = 0.0
        count = 0
        for value in values:
            if not is_missing(value):
                total += float(value)
                count += 1
        # An empty or all-missing column has count == 0; return None instead of dividing by zero.
        if count == 0:
            return None
        return total / count
    
    
    def fill_with_column_means_inplace(table: Table) -> None:
        """Same result as fill_with_column_means, but change `table` itself and return None."""
        # Mutate each eligible numeric column list in place; skip text/bool and all-missing columns.
        for values in table.values():
            if not is_numeric_column(values):
                continue
            mean_val = column_mean(values)
            if mean_val is None:
                continue  # Skip columns that have zero observed numeric values
            for row_idx in range(len(values)):
                if is_missing(values[row_idx]):
                    values[row_idx] = mean_val
    
    
    def fill_with_column_means(table: Table) -> Table:
        """Return a new table where each missing value in a numeric column is that column's mean.
    
        The mean ignores missing values. Non-numeric columns and columns with no observed
        value (all missing) are copied unchanged. The input table must not be modified.
        pandas: df.fillna(df.mean(numeric_only=True))
        """
        # Shallow-copy every column list first so the caller's input lists are never mutated.
        result: Table = {}
        for col_name, values in table.items():
            result[col_name] = list(values)
        fill_with_column_means_inplace(result)
        return result
    
    
    def group_means(keys: List[Any], values: List[Any]) -> Dict[Any, float]:
        """Compute observed mean per non-missing group key (twin of df.groupby(key)[col].mean())."""
        # totals: {group_key: sum_of_observed_values}, counts: {group_key: num_observed_values}
        totals: Dict[Any, float] = {}
        counts: Dict[Any, int] = {}
        for group_key, value in zip(keys, values):
            # pandas groupby drops NaN/None group keys by default, and mean skips missing values.
            if is_missing(group_key) or is_missing(value):
                continue
            totals[group_key] = totals.get(group_key, 0.0) + float(value)
            counts[group_key] = counts.get(group_key, 0) + 1
    
        means: Dict[Any, float] = {}
        for group_key, total in totals.items():
            means[group_key] = total / counts[group_key]
        return means
    
    
    def fill_with_group_means(table: Table, key: str) -> Table:
        """Return a new table where each missing numeric value is the mean of its row's group.
    
        Groups are the distinct values of column `key`; the key column itself is never filled.
        If the row's group has no observed value in that column, or the row's key is missing,
        use the overall column mean instead. If the column has no observed value at all,
        leave the value missing. The input table must not be modified.
        """
        keys = table[key]
        result: Table = {}
    
        for col_name, values in table.items():
            filled = list(values)
            result[col_name] = filled
    
            # Never impute the grouping key column itself or non-numeric columns.
            if col_name == key or not is_numeric_column(values):
                continue
    
            # Precompute per-group means (dict {group_key: mean}) and global fallback mean in O(n).
            per_group = group_means(keys, values)
            overall_mean = column_mean(values)
    
            for row_idx in range(len(filled)):
                if not is_missing(filled[row_idx]):
                    continue
                row_key = keys[row_idx]
                # Use the row's group mean when available; otherwise fall back to overall column mean.
                if not is_missing(row_key) and row_key in per_group:
                    filled[row_idx] = per_group[row_key]
                elif overall_mean is not None:
                    filled[row_idx] = overall_mean
    
        return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of mean imputation (replacing missing data entries with an average so downstream formulas or models do not crash on blanks) like filling blank salary cells in an HR spreadsheet. If a column holds numbers like salary, plugging in the average of the known salaries is a reasonable neutral placeholder — or even better, plugging in the average salary of that employee's team (key) — whereas trying to take the "average" of a text column like "label" makes no sense, and a column that is 100% blank has no average to plug in at all.

Why do quick first attempts often fail or run slowly? In pandas, calling df.fillna(df.mean()) without numeric_only=True crashes with a TypeError as soon as a single string column exists, and calling df.groupby("team").mean() shrinks a 1,000-row table down to one summary row per team instead of returning 1,000 row-aligned fill values. Meanwhile, in plain Python, scanning the entire n-row column afresh for every missing cell takes O(n^2) time, and checking val == float("nan") misses every single NaN (Not a Number, IEEE-754's special floating-point marker for undefined or missing values) because NaN != NaN by definition. Precomputing column (or per-group) means once in a single pass and aligning by column name or group key solves every part cleanly in linear time.

Walk through our 5-row sample table from Examples 1 and 2 (team = ["east", "east", "west", "west", "west"], score = [2.0, NaN, 8.0, NaN, 14.0], label = ["p1", "p2", None, "p4", "p5"]):

  1. Global column mean (df.fillna(df.mean(numeric_only=True))): Observed entries in score (2.0, 8.0, 14.0) average to 8.0. Both NaNs in score become 8.0 ([2.0, 8.0, 8.0, 8.0, 14.0]), while "label" is non-numeric so its None stays untouched.
  2. Per-group mean (groupby("team").transform("mean")): "east" has observed score = [2.0] (mean 2.0), and "west" has observed score = [8.0, 14.0] (mean 11.0). Row 1 gets "east"'s mean 2.0 and row 3 gets "west"'s mean 11.0, producing [2.0, 2.0, 8.0, 11.0, 14.0].

Complexity

  • Time: O(n * c) for n rows and c columns. For each column, we scan its n entries a constant number of times: once to check if it is numeric, once to sum and count non-missing numbers, and once to fill missing slots. In fill_with_group_means, building the per_group dictionary adds one more O(n) pass over (keys, values) using O(1) average-time hash-table lookups, keeping total work per column at O(n) (compared to O(n^2) if you rescanned the group on every missing row).
  • Space: O(n * c) for fill_with_column_means and fill_with_group_means because both allocate and return a new table of c lists of length n without modifying the caller's input. In-place mutation (modifying the existing data structure directly without allocating a new table) in fill_with_column_means_inplace uses O(1) extra auxiliary space, while fill_with_group_means uses O(g) temporary dictionary space (totals, counts, means) for the g <= n distinct groups of one column at a time.

Edge cases

  • All-missing (all-NaN) column: count == 0, so no mean exists. In pandas, df.mean(numeric_only=True).dropna() drops that column from the fill mapping explicitly; in Python, column_mean returns None and we skip the column so its NaN/None entries remain intact.
  • Non-numeric text or mixed-type columns: Left completely unchanged, preserving any None or NaN inside them.
  • Boolean columns: In Python, bool subclasses int (isinstance(True, int) is True), so checking isinstance(value, bool) first prevents averaging [True, None, False] to 0.5. Similarly in pandas, df.select_dtypes(include="number") excludes bool and nullable boolean columns, whereas df.mean(numeric_only=True) treats booleans as 0/1 and raises a TypeError when trying to write 0.5 back into a nullable boolean column.
  • Nullable integer columns in pandas: Standard int64 columns with NaN are already cast to float64, whereas pandas nullable Int64 columns reject fractional fill values like 2.5 with a TypeError unless cast to Float64 or rounded first.
  • Group with zero observed values, or row with a missing group key: When an entire group has zero observed entries in a column (like "ops" in Example 3) or table[key][i] itself is None/NaN, no group mean exists, so chaining .fillna(df[num_cols].mean()) (and elif overall_mean is not None: in Python) cleanly falls back to the global column mean.
  • Numeric group key column: If "tier" holds integers [1, 1, 2, NaN], excluding col_name == key (and .drop("tier", errors="ignore") in pandas) prevents accidentally imputing missing group IDs with an average ID like 1.33.
  • Empty table ({}) or zero-row columns ({"score": []}): Handled safely without ZeroDivisionError because count == 0 returns None.

Common mistakes

  • Omitting numeric_only=True in df.mean(): Raises TypeError on any DataFrame containing string or object columns in pandas >= 2.0.
  • Chained inplace=True on a column subset (df[num_cols].fillna(..., inplace=True)): Chained assignment (indexing a slice and then mutating that temporary result) modifies a copy rather than df, leaving df full of NaNs; under pandas Copy-on-Write even single-column df["score"].fillna(m, inplace=True) leaves df unchanged.
  • Writing df = df.fillna(..., inplace=True): In pandas 1.x and 2.x, inplace=True returns None, overwriting df with None. Either assign the returned copy (df = df.fillna(...)) or mutate df directly (df.fillna(..., inplace=True)), never both.
  • Using groupby("team").mean() instead of groupby("team").transform("mean"): groupby().transform() broadcasts each group's aggregate back to every original row's index, whereas .groupby().mean() returns one row per distinct group and will not align with df's row index.
  • Checking value == float("nan"): Always evaluates to False in Python and NumPy; always use math.isnan or pd.isna.
  • Computing means before splitting train and test sets: Fitting column or group means on the combined dataset causes data leakage (letting test-set statistics influence training features); always fit means on train only and reuse those exact saved means on validation, test, and live inference.

Follow-up questions

  • How does replacing missing entries with the column average affect feature variance and skewed distributions, and what alternatives help? Plugging the exact same constant mean into every missing row artificially shrinks the column's variance and weakens correlations with other features: for score = [2, NaN, 8, NaN, 14], sample variance on the 3 observed points is ((2 - 8)^2 + 0 + (14 - 8)^2) / 2 = 36.0, whereas after filling [2, 8, 8, 8, 14] it drops in half to 72 / 4 = 18.0! When values are heavily right-skewed (like household income [30k, 35k, 40k, 1000k, NaN]), the mean (276.25k) is pulled far away from typical rows, so median imputation (37.5k) is much safer; and whenever missingness itself carries predictive signal (such as applicants skipping an optional debt field), add a binary score_is_missing = df["score"].isna() indicator column alongside the imputed value.
  • How do you prevent data leakage when applying column or grouped mean imputation across training and test splits? Fit the global means and per-group mean lookup dictionary strictly on the training split, store those learned numbers as model state, and apply them unchanged to validation, test, and production rows (falling back to the stored training global mean if a test row belongs to a brand-new unseen group). In scikit-learn, wrapping SimpleImputer(strategy="mean") inside a Pipeline guarantees that during k-fold cross-validation each fold computes its own training means without ever peeking at its held-out validation fold.

python train_means = train_df.mean(numeric_only=True) train_filled = train_df.fillna(train_means) test_filled = test_df.fillna(train_means) # reuse train_means, never test_df.mean()!

  • Why can per-group mean imputation backfire on tiny groups, and how does smoothing fix it? Per-group means shine when groups genuinely differ and have plenty of data, but when a group has only 1 or 2 observed rows, its sample mean is mostly random noise (an outlier row makes the whole group's fill value extreme). The standard fix is shrinkage (blending noisy small-group estimates toward the stable global mean): blended_mean = (n_g * group_mean + m * global_mean) / (n_g + m) with a smoothing weight m such as 5-10 virtual rows — so a group like "east" with n_g = 1 row (2.0), global_mean = 8.0, and m = 5 gets (1 * 2.0 + 5 * 8.0) / 6 = 7.0, whereas a group with n_g = 500 rows stays almost entirely at its own group_mean.

Follow-up questions

Similar questions

More Aeonea interview questions

All 3 Aeonea questions →