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
Noneor an IEEE-754 floating-pointNaN(float("nan")). - A column is numeric when every non-missing cell is an
intorfloat, excludingbool(TrueandFalseare treated as non-numeric). - Arithmetic means are computed strictly over observed (non-missing) entries as
floatvalues.
Implement three functions (and be ready to explain their concise pandas counterparts):
fill_with_column_means(table: Table) -> Table: Return a new table (without mutatingtableor 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.fill_with_column_means_inplace(table: Table) -> None: Perform the exact same column-mean replacement by mutatingtable's lists directly in place and returningNone.fill_with_group_means(table: Table, key: str) -> Table: Return a new table (without mutatingtable) where each missing cell in a numeric column other thankeyis filled with the mean of observed values in that column among rows sharing the same non-missingtable[key]value. Never fill the grouping columnkeyitself. If a row'skeyentry 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
tablehave equal length0 <= n <= 10^5, and0 <= len(table) <= 200. - For
fill_with_group_means(table, key),keyis guaranteed to be an existing column key intable, and observed group keys are hashable. - Non-in-place functions (
fill_with_column_meansandfill_with_group_means) must never mutatetableor its inner lists. - Aim for
O(n * c)time acrossnrows andccolumns rather than rescanning a column on every missing cell.
Step-by-step walkthrough
Understand the goal and set up a 5-row sample table
We have a column-oriented table containing missing cells (
NaNorNone) 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 returnNone. - 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
pandasexpressions first. Because our test runner uses the Python standard library withoutpandas, we show both the exactpandasidioms and their pure-Python counterparts onTable = 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- Global column means (
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, ignoresNaNs automatically (skipna=Trueby default), and returns aSeriesindexed by column name:score -> 8.0,bonus -> 40.0,empty -> NaN. Passingnumeric_only=Trueis essential — sincepandas 2.0, omitting it raises aTypeErrorwhenever the DataFrame contains string columns like"team"or"label".df.fillna(series)matches theSeriesindex labels againstdf's column names, fillingscorewith8.0andbonuswith40.0while ignoring"team"and"label"completely.
If your DataFrame also contains nullable
booleancolumns (True/False/<NA>), selecting strictly number-typed columns withselect_dtypes(include="number")is even safer becausemean(numeric_only=True)treats booleans as0/1numbers whereasselect_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())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:NaN != NaN: In IEEE-754 floating-point math,float("nan") == float("nan")evaluates toFalse! Always detectNaNusingmath.isnan(value)after checkingisinstance(value, float).boolsubclassesint: In Python,isinstance(True, int)isTrue(True == 1andFalse == 0). Sois_numeric_columnmust rejectisinstance(value, bool)before accepting(int, float), matchingselect_dtypes(include="number").- Zero observed values: If every entry in a column is missing,
count == 0— returningNoneavoidsZeroDivisionError(mirroring howpandasreturnsNaN).
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 / countFill column means in-place vs. returning a new copy
In
pandas, there are two clean ways to updatedfdirectly 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=Truepitfalls inpandas:- Never call
.fillna(..., inplace=True)on a column slice likedf[num_cols].fillna(..., inplace=True)ordf["score"].fillna(m, inplace=True). Indexingdf[num_cols]builds a separate copy, and underpandasCopy-on-Write evendf["score"]behaves like a copy — so mutating that temporary slice leavesdfitself full ofNaNs! - Never combine assignment with
inplace=True(df = df.fillna(..., inplace=True)), because inpandas 1.x/2.xinplace=TruereturnsNoneand wipes out your variable.
In our pure-Python implementation,
fill_with_column_means_inplacemutates each eligible column list directly and returnsNone, whilefill_with_column_meansshallow-copies each column list first (list(values)) and delegates tofill_with_column_means_inplaceso 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- Never call
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 collapses5rows down to2summary rows ("east"and"west"). Instead,pandasprovides.transform("mean"), which broadcasts each group's mean back into a DataFrame of the exact same5-row shape and index asdf: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:
- Never fill the grouping column itself:
.drop("team", errors="ignore")protects the key column even when group IDs are integers (1, 2, ...). - Group with zero observed values: As in Example 3 (
dept = "ops"),transform("mean")putsNaNfor"ops", and the chained.fillna(df[num_cols].mean())seamlessly falls back to the overall column mean! - Missing group key (
None/NaN): By defaultgroupbyskipsNaNkeys, sotransform("mean")outputsNaNon that row, and the second.fillna(...)fills it with the overall column mean.
In pure Python,
group_meansaccumulatestotalsandcountsper non-missing key in a singleO(n)pass, andfill_with_group_meanschecksper_groupfirst before falling back tooverall_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- Never fill the grouping column itself:
Skip zero-observation columns explicitly
In
df.fillna(df.mean(numeric_only=True)), an all-NaNcolumn likeemptystaysNaNbecause its mean isNaN, and replacingNaNwithNaNis a no-op. Making that skip explicit with.dropna()on the meansSeriesis cleaner and faster becausepandasnever even visits all-NaNcolumns duringfillna: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-
NaNcolumns rather than skip them, that would bedf.dropna(axis=1, how="all"); skipping keeps those columns intact.) In our Python code,if mean_val is None: continueandelif overall_mean is not None:implement that exact explicit skip.Trace Examples 1, 2, and 3 step by step
Let's compare
fill_with_column_meansandfill_with_group_meansside 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 fillsscore[1]with8.0(pulled upward by"west"'s larger numbers), whereas group imputation fillsscore[1]with2.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 row1with its group mean10.0, while"ops"(zero observed values) andNone(missing key) fall back cleanly tooverall_mean = 30.0.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"]):
- Global column mean (
df.fillna(df.mean(numeric_only=True))): Observed entries inscore(2.0, 8.0, 14.0) average to8.0. BothNaNs inscorebecome8.0([2.0, 8.0, 8.0, 8.0, 14.0]), while"label"is non-numeric so itsNonestays untouched. - Per-group mean (
groupby("team").transform("mean")):"east"has observedscore = [2.0](mean2.0), and"west"has observedscore = [8.0, 14.0](mean11.0). Row1gets"east"'s mean2.0and row3gets"west"'s mean11.0, producing[2.0, 2.0, 8.0, 11.0, 14.0].
Complexity
- Time:
O(n * c)fornrows andccolumns. For each column, we scan itsnentries 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. Infill_with_group_means, building theper_groupdictionary adds one moreO(n)pass over(keys, values)usingO(1)average-time hash-table lookups, keeping total work per column atO(n)(compared toO(n^2)if you rescanned the group on every missing row). - Space:
O(n * c)forfill_with_column_meansandfill_with_group_meansbecause both allocate and return a new table ofclists of lengthnwithout modifying the caller's input. In-place mutation (modifying the existing data structure directly without allocating a new table) infill_with_column_means_inplaceusesO(1)extra auxiliary space, whilefill_with_group_meansusesO(g)temporary dictionary space (totals,counts,means) for theg <= ndistinct groups of one column at a time.
Edge cases
- All-missing (
all-NaN) column:count == 0, so no mean exists. Inpandas,df.mean(numeric_only=True).dropna()drops that column from the fill mapping explicitly; in Python,column_meanreturnsNoneand we skip the column so itsNaN/Noneentries remain intact. - Non-numeric text or mixed-type columns: Left completely unchanged, preserving any
NoneorNaNinside them. - Boolean columns: In Python,
boolsubclassesint(isinstance(True, int)isTrue), so checkingisinstance(value, bool)first prevents averaging[True, None, False]to0.5. Similarly inpandas,df.select_dtypes(include="number")excludesbooland nullablebooleancolumns, whereasdf.mean(numeric_only=True)treats booleans as0/1and raises aTypeErrorwhen trying to write0.5back into a nullablebooleancolumn. - Nullable integer columns in
pandas: Standardint64columns withNaNare already cast tofloat64, whereaspandasnullableInt64columns reject fractional fill values like2.5with aTypeErrorunless cast toFloat64or 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) ortable[key][i]itself isNone/NaN, no group mean exists, so chaining.fillna(df[num_cols].mean())(andelif 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], excludingcol_name == key(and.drop("tier", errors="ignore")inpandas) prevents accidentally imputing missing group IDs with an average ID like1.33. - Empty table (
{}) or zero-row columns ({"score": []}): Handled safely withoutZeroDivisionErrorbecausecount == 0returnsNone.
Common mistakes
- Omitting
numeric_only=Trueindf.mean(): RaisesTypeErroron any DataFrame containing string or object columns inpandas >= 2.0. - Chained
inplace=Trueon a column subset (df[num_cols].fillna(..., inplace=True)): Chained assignment (indexing a slice and then mutating that temporary result) modifies a copy rather thandf, leavingdffull ofNaNs; underpandasCopy-on-Write even single-columndf["score"].fillna(m, inplace=True)leavesdfunchanged. - Writing
df = df.fillna(..., inplace=True): Inpandas 1.xand2.x,inplace=TruereturnsNone, overwritingdfwithNone. Either assign the returned copy (df = df.fillna(...)) or mutatedfdirectly (df.fillna(..., inplace=True)), never both. - Using
groupby("team").mean()instead ofgroupby("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 withdf's row index. - Checking
value == float("nan"): Always evaluates toFalsein Python and NumPy; always usemath.isnanorpd.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
trainonly 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 the3observed points is((2 - 8)^2 + 0 + (14 - 8)^2) / 2 = 36.0, whereas after filling[2, 8, 8, 8, 14]it drops in half to72 / 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 binaryscore_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, wrappingSimpleImputer(strategy="mean")inside aPipelineguarantees 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
1or2observed 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 weightmsuch as5-10virtual rows — so a group like"east"withn_g = 1row (2.0),global_mean = 8.0, andm = 5gets(1 * 2.0 + 5 * 8.0) / 6 = 7.0, whereas a group withn_g = 500rows stays almost entirely at its owngroup_mean.
Follow-up questions
- How does replacing missing entries with the column average affect feature variance and skewed distributions, and what alternatives help?
- How do you prevent data leakage when applying column or grouped mean imputation across training and test splits?
- Why can per-group mean imputation backfire on tiny groups, and how does smoothing fix it?
Similar questions
- Target-Sum Index Pair
- Single-Game Tennis Scoreboard
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
More Aeonea interview questions
- Target-Sum Index Pair Medium
- Single-Game Tennis Scoreboard Medium