Column-wise Gap Filling with Mean, Median or Mode
Arrays & HashingAuto-graded · 22 test casesLast updated
Fill None cells in a table column by column with the mean, median or smallest-most-frequent value of the observed entries, without mutating the input.
You are given a table as a list of rows. A cell holds a value, or None if it is missing. Write a function that fills every missing cell using a statistic computed from the other cells in the same column, and returns the completed table.
Inputs
table: a list of rows, each a list of cells. Every row has the same length as the first row. A cell is eitherNoneor a value. For"mean"and"median"the values are numbers. For"mode"the values can be any mutually comparable, hashable type (for example numbers or strings).method: one of"mean","median","mode".
Output
A new table of the same shape in which each None has been replaced by its column's replacement value. Cells that were not None stay unchanged. The input table and its rows must not be modified.
Replacement rules (per column)
Let the observed values of a column be all its cells that are not None.
"mean": the arithmetic mean of the observed values."median": the middle observed value after sorting. If the count is even, the average of the two middle values."mode": the most frequent observed value. If several values tie for the highest frequency, use the smallest of them.- If a column has no observed values, its replacement is
None, so the column stays entirely missing.
Error and edge-case behavior
- If
tableis empty, return[]. - If
methodis not one of the three allowed strings, raiseValueError. This is checked lazily: the check happens only when a column that has at least one observed value is processed. A table whose columns are all entirely missing, or whose rows have width 0, therefore returns normally even with an invalidmethod. - Columns are handled independently of each other.
Constraints
- 0 ≤ number of rows ≤ 10^4
- 0 ≤ number of columns ≤ 100
- All rows have the same length.
- Within one column, observed values are mutually comparable. For
"mean"and"median"they are numeric. - The returned table must be a fresh structure. Mutating the input is not allowed.
Examples
Example 1
Input: fill_missing_cells([[1, 2], [3, None], [None, 2]], 'mean')
Output: [[1, 2], [3, 2], [2, 2]]
Example 2
Input: fill_missing_cells([[1, None], [5, 8], [9, None], [None, 8]], 'median')
Output: [[1, 8], [5, 8], [9, 8], [5, 8]]
Example 3
Input: fill_missing_cells([['1', None], ['2', '2'], [None, '1'], ['1', None]], 'mode')
Output: [['1', '1'], ['2', '2'], ['1', '1'], ['1', '1']]
Hints
Hint 1
Handle each column separately. First gather the cells in that column that are not None, then derive one replacement value from them.
Hint 2
For the median, sort the observed values and check the parity of their count. For the mode, count occurrences, find the highest count, and take the minimum among the values reaching it.
Hint 3
Copy each row before writing, and remember the order of checks: an empty column yields None without ever looking at the method, while an unknown method only raises once a column with observed data is reached.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Work column by column, since a column's replacement depends only on its own observed values.
- If the table is empty, return
[]. - Copy every row so the caller's data is never modified.
- For each column, collect the cells that are not
None. - Compute one replacement value:
- No observed values: the replacement is
None. "mean": sum divided by count."median": sort, then take the middle element for an odd count, or the average of the two middle elements for an even count."mode": count occurrences with aCounter, find the highest count, and take the smallest value among those reaching it.- Anything else: raise
ValueError.
- No observed values: the replacement is
- Write the replacement into every cell of that column that was
Nonein the copy.
Why it is correct
- Each statistic uses only the observed values of its own column, so columns do not influence each other.
- Only cells that were
Noneare overwritten, so observed data is preserved exactly. - The median handles both parities explicitly, so even-sized columns give the average of the two central values.
- Taking the minimum over tied frequencies makes the mode independent of row order, so the output is deterministic.
- An all-missing column produces
None, which leaves it unchanged. Because the method check sits after that branch, theValueErrorbehavior matches the stated lazy rule. - Copying rows with
row[:]guarantees the input is not mutated.
Complexity
With n rows and m columns:
- Time: O(n·m) for mean and mode, O(m · n log n) for median because of sorting.
- Space: O(n·m) for the output copy, plus O(n) for one column's observed values or counter at a time.
Reference solution
from collections import Counter
from typing import Any, List
def fill_missing_cells(table: List[List[Any]], method: str) -> List[List[Any]]:
if not table:
return []
width = len(table[0])
result = [row[:] for row in table]
for col in range(width):
observed = [row[col] for row in table if row[col] is not None]
if not observed:
replacement = None
elif method == "mean":
replacement = sum(observed) / len(observed)
elif method == "median":
ordered = sorted(observed)
mid = len(ordered) // 2
if len(ordered) % 2:
replacement = ordered[mid]
else:
replacement = (ordered[mid - 1] + ordered[mid]) / 2
elif method == "mode":
counts = Counter(observed)
top = max(counts.values())
replacement = min(v for v, c in counts.items() if c == top)
else:
raise ValueError("method must be 'mean', 'median', or 'mode'")
for row in result:
if row[col] is None:
row[col] = replacement
return result