What you will be able to do
- Pick mean, median or mode as the fill value for a column from its type and distribution
- Compute a column's mean, median or mode in Spark, and explain why a distributed median is approximate
- Write computed fill values back to a Spark DataFrame with df.na.fill, respecting its type-matching rules
- Use SimpleImputer in a scikit-learn Pipeline, including most_frequent for string categories
- Find where an AutoML experiment lets you override the imputation method for each column
Key concept
Statistic-based imputation — Each null in a column is replaced with one value computed from that column's observed values: the mean, the median, or the mode. That value is learned once, on training data, and then reused unchanged wherever the column is filled.
1.Imputation fills nulls instead of discarding rows
A missing value forces a choice: throw away the record, or fill the gap with a plausible value. Spark makes the first option a single call. df.na.drop() returns a new DataFrame without any row that contains a null or NaN. A row with one missing field is still mostly real data, though, and dropping it throws away every observed value in that row. Imputation keeps the row and replaces the gap with a value inferred from the observed part of the same column.
The simplest imputers are univariate. Each column is filled from its own non-missing values with one of three statistics: the mean (the column average), the median (the middle value once the column is sorted) or the mode (the most frequent value). The column's type and shape decide which one to use. Mean and median only exist for numbers. The mode is the only one of the three that also works for a string column such as payment_method.
Here is a worked case. The median of the values 1, 2, 3, 4 and 5 is 3, and so is their mean. Now replace the 5 with 500. The median is still 3, because the middle element has not changed. The mean jumps to 102. A home filled with 102 would look nothing like the bulk of the data. That is why the median is the fill value for skewed columns or columns with outliers, and the mean is for roughly symmetric numeric columns. For a continuous column like square footage, the mode is usually a poor choice: many values occur only once, so the 'most frequent' value may not be typical at all. Dropping the rows avoids imputing anything, but it also loses the rest of each record. The full trade-offs between the three statistics are covered in comparing mean, median and mode imputation. The rest of this page covers how to compute and apply the value.
| Column | Fill with | Reason |
|---|---|---|
| Numeric, roughly symmetric | mean | The average represents the centre well when nothing pulls it |
| Numeric, skewed or with outliers | median | The middle value ignores how extreme the tail is |
| Categorical (strings, category codes) | most frequent (mode) | Mean and median are undefined for labels |
Checkpoint 1 of 8· Check yourself
A training DataFrame has a string column payment_method (values such as 'card', 'cash', 'voucher'). A few rows have a null in it, and every other field in those rows is observed. How should you handle these nulls?
Mean and median exist only for numbers, so a string column has to be filled with its most frequent value. Dropping the rows would also throw away every other observed value in each of them.
“The SimpleImputer class also supports categorical data represented as string values or pandas categoricals when using the 'most_frequent' or 'constant' strategy”Source: scikit-learn.org
Checkpoint 2 of 8· Exam question
A Databricks ML engineer is preparing a training set for a housing price model. The square_footage column has a small number of missing values, and a histogram shows the feature is heavily right-skewed with several extreme outliers on the high end. Which imputation approach best preserves the typical value of this feature?
Correct answer: A — Impute the missing entries with the column median, because the median is not pulled toward the extreme high-end values and stays close to the bulk of the distribution.
- A. The median is a robust measure of central tendency: it is determined by rank rather than magnitude, so a few extreme high-end values in a right-skewed distribution do not distort it. This makes it the recommended strategy for skewed numeric features with outliers.
- B. The mean is sensitive to extreme values, so in a right-skewed distribution with outliers it would be pulled upward and would overstate the typical square footage, making imputed rows unrepresentative.
- C. The most frequent value (mode) strategy is intended for categorical or discrete features with repeated values, not for a continuous numeric feature like square footage where most values are unique.
- D. Dropping rows discards potentially useful training data unnecessarily when a small number of missing values in one column can be imputed reasonably; this is a valid fallback only when imputation itself would be misleading, not the best first choice here.
2.Computing the mean, median and mode in Spark
Spark's aggregate functions compute all three statistics and skip nulls. sf.mean returns the average and is an alias of avg. In the example below, the age column holds None, 2 and 4, and the result is 3.0. The null was left out of both the sum and the count, so it did not drag the average toward zero. This is the behaviour you want, because the fill value should describe only the values that were observed.
import pyspark.sql.functions as sf
df = spark.createDataFrame([(1982, None), (1990, 2), (2000, 4)], ["birth", "age"])
df.select(sf.mean("age")).show()
+--------+
|avg(age)|
+--------+
| 3.0|
+--------+sf.median(col) returns the median of the values in a group. sf.mode(col, deterministic=False) returns the most frequent value. The mode can be ambiguous. If two categories tie for most frequent, Spark may return either one, so two runs over the same data could fill the column differently. Passing deterministic=True makes Spark return the lowest of the tied values every time.
The tie lets Spark return either value, so the imputed region can change from one run to the next. Call sf.mode('region', True) to get the lowest value every time. Or compute the mode once and store it.
At scale, the median is an approximation. An exact median needs a global sort, and that is expensive on a multi-billion-row table. Spark instead uses approxQuantile(col, [0.5], relativeError), a variation of the Greenwald-Khanna algorithm. It skips nulls and returns a value whose rank is guaranteed to be within relativeError of the true middle. Setting relativeError to 0 forces the exact quantile, at a much higher cost. pyspark.ml.feature.Imputer(strategy='median') fills from the same kind of distributed approximate median. It runs across the executors without collecting the column to the driver, and the value it fills is close to the exact median but not guaranteed to equal it. Approximate quantiles themselves are covered in approximate quantiles in Spark (approxQuantile, percentile_approx).
Checkpoint 3 of 8· Fill the gap
Each of -10, 0 and 10 appears once, so all three tie for most frequent. A scheduled job must get the same fill value, -10, on every run. Which argument completes the call?
from pyspark.sql import functions as sf
df = spark.createDataFrame([(-10,), (0,), (10,)], ["col"])
df.select(sf.mode("col", ? )).show()The second argument of sf.mode is deterministic. When values tie, True makes Spark return the lowest one every time. False is the default, and so is leaving the argument out: with either, Spark may return any of the tied values, so the fill value can change between runs.
Source: docs.databricks.comCheckpoint 4 of 8· Exam question
A team needs to impute missing values in a numeric sensor_reading column of a multi-billion-row Spark DataFrame using the median, without collecting the full column to the driver. Which approach correctly fills the missing values at this scale, and what should the team understand about the result?
Correct answer: A — Use pyspark.ml.feature.Imputer with strategy='median'; it computes the median across executors with approxQuantile, so the filled value is a close approximation rather than an exact median.
- A.
pyspark.ml.feature.Imputerscales to distributed data and, for the median strategy, internally relies onapproxQuantilewith a small relative error, so the imputed value is a close but approximate median rather than an exact one. - B. Calling
.toPandas()on a multi-billion-row DataFrame pulls the entire dataset into driver memory, which is exactly what the team wants to avoid at this scale, even though the resulting median would be exact. - C. The mean strategy is also computed at this scale, but the claim that it is the only strategy guaranteeing an exact statistic is incorrect; a distributed sum-and-count mean is exact, while it is the median that is approximated, not the mean that fails.
- D.
dbutils.data.summarize()is a diagnostic utility for displaying descriptive statistics in a notebook; it is not built to hand its output into an imputation pipeline, and manually wiring it up is not the standard distributed approach.
3.Writing the value back with na.fill
Computing the statistic does not change the DataFrame. You write it back with df.na.fill(value, subset), which is the same method as df.fillna. Both return a new DataFrame with nulls replaced. The value must be a literal int, float, boolean or string, not a Spark Column. In practice, you run the aggregate first, pull the single number out of its one-row result into a Python variable, and pass that variable to fill.
df = spark.createDataFrame([
(10, 80.5, "Alice", None),
(5, None, "Bob", None),
(None, None, "Tom", None),
(None, None, None, True)],
schema=["age", "height", "name", "bool"])
df.na.fill(50).show()
# +---+------+-----+----+
# |age|height| name|bool|
# +---+------+-----+----+
# | 10| 80.5|Alice|NULL|
# | 5| 50.0| Bob|NULL|
# | 50| 50.0| Tom|NULL|
# | 50| 50.0| NULL|true|
# +---+------+-----+----+fill only writes to columns whose type matches the value. The integer 50 filled age and was stored as 50.0 in the float column height, but name and bool kept their nulls. Columns listed in subset that don't match the value's type are silently skipped as well, so a typo in a type is easy to miss. A real imputation needs a different value per column, such as a median for height and a mode for name. The dict form handles that: {'age': 50, 'name': 'unknown'} maps each column to its own value. With a dict, subset is ignored.
| Call | Columns filled | Columns left with NULL |
|---|---|---|
| df.na.fill(50) | age, height | name, bool |
| df.na.fill(False) | bool | age, height, name |
| df.na.fill({'age': 50, 'name': 'unknown'}) | age, name | height, bool |
| df.na.fill(value='Spark', subset='name') | name | age, height, bool |
Compute the fill value on the training split only. Then pass that same literal to na.fill for validation, test and scoring data. Recomputing the median on the test set lets information about the test set into preprocessing. It also means production rows get filled with a value the model never saw during training. The general rule is covered in fit preprocessing on training data only (leakage-safe Pipeline). For na.fill, it means you save the number and reuse it.
Checkpoint 5 of 8· Match them up
Use the example DataFrame from this section: age is an integer column, height is float, name is string and bool is boolean, and each has nulls. Match each call to the result it produces.
Tap a term, then the definition that fits it.
A single value only fills columns whose type matches it, and that includes columns named in subset, so 'unknown' leaves the integer age column alone. A dict gives each column its own value and fills only the columns it names.
“Columns in subset that do not have a matching data type for value are ignored.”Source: docs.databricks.com
Sources9
4.SimpleImputer for pandas data and scikit-learn pipelines
When a Spark DataFrame has been converted with toPandas() for a single-node scikit-learn model, imputation moves to sklearn.impute.SimpleImputer. Its strategy is 'mean', 'median', 'most_frequent' (the mode) or 'constant'. Like Spark's Imputer, it is fitted and then applied: fit learns one statistic per column, and transform fills any later array with those stored values.
>>> import numpy as np
>>> from sklearn.impute import SimpleImputer
>>> imp = SimpleImputer(missing_values=np.nan, strategy='mean')
>>> imp.fit([[1, 2], [np.nan, 3], [7, 6]])
SimpleImputer()
>>> X = [[np.nan, 2], [6, np.nan], [7, 6]]
>>> print(imp.transform(X))
[[4. 2. ]
[6. 3.666]
[7. 6. ]]The output shows the train-only rule at work. The 4 is the mean of 1 and 7, and the 3.666 is the mean of 2, 3 and 6. Both come from the array passed to fit, not from X. missing_values sets what counts as missing. It defaults to np.nan, but a sentinel such as -1 also works.
For a string column like payment_method, only two strategies work: 'most_frequent' and 'constant'. Both accept string values and pandas categoricals. 'mean' and 'median' have no meaning for labels, even if the categories have been converted to integer codes, because averaging codes produces a category nobody chose. SimpleImputer can be a step in a scikit-learn Pipeline, so the mode is learned when the pipeline is fitted and reused when it predicts. Spark's pyspark.ml.feature.Imputer is the wrong tool for this job. It works on Spark DataFrames, not pandas objects, and it does not plug into a scikit-learn Pipeline.
Checkpoint 6 of 8· Check yourself
You have a pandas DataFrame from toPandas() with a categorical column payment_method that has some nulls. The column will feed a scikit-learn Pipeline, and its nulls should get the most common category. Which imputation step fits?
For string or categorical data, SimpleImputer supports only 'most_frequent' and 'constant'. Taking the median or mean of category codes gives a category nobody chose. Spark's Imputer works on Spark DataFrames, not pandas objects, and it does not plug into a scikit-learn Pipeline.
“The SimpleImputer class also supports categorical data represented as string values or pandas categoricals when using the 'most_frequent' or 'constant' strategy”Source: scikit-learn.org
Checkpoint 7 of 8· Exam question
A data scientist has converted a Spark DataFrame to pandas and needs to fill missing values in a categorical column, payment_method, before fitting a scikit-learn model. The team wants an approach that plugs into a scikit-learn Pipeline and fills gaps with the most common category. Which approach correctly satisfies this requirement?
Correct answer: A — Use SimpleImputer(strategy='most_frequent') on the column, since it computes the mode of the observed categories and works with non-numeric string values inside a Pipeline.
- A.
SimpleImputer(strategy='most_frequent')explicitly supports string and categorical dtypes and fills gaps with the mode, and it is a standard scikit-learn transformer that composes cleanly inside aPipeline. - B.
pyspark.ml.feature.Imputeris a Spark ML transformer built for numeric input columns and Spark DataFrames; it does not accept pandas categorical columns and cannot be dropped into a scikit-learnPipeline. - C. The median strategy requires numeric input and would raise an error or produce a meaningless value on a string column, since category labels have no ordering to compute a median over.
- D. The mean strategy is only defined for numeric data; casting a categorical column to strings and averaging it does not compute a mode and would fail rather than fill the column with the most common label.
5.Setting the imputation strategy per column in AutoML
Databricks AutoML imputes nulls itself. By default, it picks a method for each column from that column's type and content. How AutoML reads column types is covered in AutoML feature selection: column types, semantic types and imputation. On Databricks Runtime 10.4 LTS ML and above, you can override that choice for each column. In the UI, choose a method from the Impute with drop-down in the table schema. In the API, pass the imputers argument to databricks.automl.regress or classify. It is a dict keyed by column name, and each value is a strategy string or a dict of settings.
An override has a side effect. When you set a non-default imputation method on a column, AutoML stops running semantic type detection on it. For example, AutoML would normally treat a string column of numbers as numeric, but it won't for that column once you set its imputation method yourself. The data type you supply is the one AutoML uses. Check that the type is correct before you override imputation on a column.
Checkpoint 8 of 8· Check yourself
In a databricks.automl.regress run on Databricks Runtime 10.4 LTS ML, you want AutoML to fill nulls in the skewed square_footage column with the median, not with the method it would pick by default. How do you request this through the API?
The imputers argument is a dict keyed by column name, and each value is a strategy string or a dict of settings. na.fill takes a literal value, so the string 'median' would not compute anything, and fill skips square_footage anyway because a string value does not match a numeric column.
“imputers: Optional[Dict[str, Union[str, Dict[str, Any]]]] = None”Source: docs.databricks.com
Sources
(12)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Returns a new DataFrame omitting rows with null or NaN values.”
↩︎ Imputation fills nulls instead of discarding rows - 2.https://scikit-learn.org/stable/modules/impute.htmlSecondary source
“A better strategy is to impute the missing values, i.e., to infer them from the known part of the data.”
↩︎ Imputation fills nulls instead of discarding rows“using the statistics (mean, median or most frequent) of each column in which the missing values are located”
↩︎ Imputation fills nulls instead of discarding rows“The SimpleImputer class also supports categorical data represented as string values or pandas categoricals when using the 'most_frequent' or 'constant' strategy”
↩︎ SimpleImputer for pandas data and scikit-learn pipelines“Both SimpleImputer and IterativeImputer can be used in a Pipeline as a way to build a composite estimator that supports imputation.”
↩︎ SimpleImputer for pandas data and scikit-learn pipelines“A better strategy is to impute the missing values, i.e., to infer them from the known part of the data.”
↩︎ Key concept“The SimpleImputer class also supports categorical data represented as string values or pandas categoricals when using the 'most_frequent' or 'constant' strategy”
↩︎ Exam trap 4“The SimpleImputer class also supports categorical data represented as string values or pandas categoricals when using the 'most_frequent' or 'constant' strategy”
↩︎ Checkpoint - 3.
“For example 0.0 is the minimum, 0.5 is the median, 1.0 is the maximum.”
↩︎ Imputation fills nulls instead of discarding rows“If set to zero, the exact quantiles are computed, which could be very expensive.”
↩︎ Computing the mean, median and mode in Spark“Null values will be ignored in numerical columns before calculation.”
↩︎ Computing the mean, median and mode in Spark“If set to zero, the exact quantiles are computed, which could be very expensive.”
↩︎ Exam trap 2 - 4.
“Returns the average of the values in a group. An alias of avg.”
↩︎ Computing the mean, median and mode in Spark - 5.
“Returns the median of the values in a group.”
↩︎ Computing the mean, median and mode in Spark - 6.
“either any of values is returned if deterministic is false or is not defined, or the lowest value is returned if deterministic is true”
↩︎ Computing the mean, median and mode in Spark“either any of values is returned if deterministic is false or is not defined, or the lowest value is returned if deterministic is true”
↩︎ Exam trap 3 - 7.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframestatfunctions/approxQuantileOfficial docs
“This method implements a variation of the Greenwald-Khanna algorithm with some speed optimizations.”
↩︎ Computing the mean, median and mode in Spark - 8.
“Returns the contents of this DataFrame as Pandas pandas.DataFrame.”
↩︎ Computing the mean, median and mode in Spark“Returns the contents of this DataFrame as Pandas pandas.DataFrame.”
↩︎ SimpleImputer for pandas data and scikit-learn pipelines - 9.
“DataFrame.fillna and DataFrameNaFunctions.fill are aliases of each other.”
↩︎ Writing the value back with na.fill“The replacement value must be an int, float, boolean, or string.”
↩︎ Writing the value back with na.fill“If the value is a dict, then subset is ignored and value must be a mapping from column name (string) to replacement value.”
↩︎ Writing the value back with na.fill“Columns specified in subset that do not have matching data types are ignored.”
↩︎ Writing the value back with na.fill“Columns specified in subset that do not have matching data types are ignored.”
↩︎ Exam trap 1 - 10.
“By default, AutoML selects an imputation method based on the column type and content.”
↩︎ Setting the imputation strategy per column in AutoML“In the UI, select a method from the drop-down in the Impute with column in the table schema.”
↩︎ Setting the imputation strategy per column in AutoML“If you specify a non-default imputation method, AutoML does not perform semantic type detection.”
↩︎ Setting the imputation strategy per column in AutoML“If you specify a non-default imputation method, AutoML does not perform semantic type detection.”
↩︎ Exam trap 5 - 11.
“imputers: Optional[Dict[str, Union[str, Dict[str, Any]]]] = None,”
↩︎ Setting the imputation strategy per column in AutoML“imputers: Optional[Dict[str, Union[str, Dict[str, Any]]]] = None”
↩︎ Checkpoint
Also cited
“Columns in subset that do not have a matching data type for value are ignored.”
↩︎ Checkpoint