What you will be able to do
- Explain why imputing a column's missing values from its own statistic is often better than dropping rows
- Compute a column's mean, median, and mode with the PySpark sf.mean, sf.median, and sf.mode functions
- Pick mode for categorical columns, and show from the numbers why one extreme value pulls the mean but not the median
Key concept
Univariate statistic imputation — You replace each missing entry in a column with one summary value (the mean, median, or most frequent value) worked out from the values that column does have. No other column is used, so the main decision is which statistic suits that column.
1.Drop the row, or fill the gap?
Real datasets have holes in them. In a Spark DataFrame a missing value appears as NULL. In pandas or NumPy it is usually NaN. Many estimators can't use these rows as they are. The scikit-learn guide says its estimators assume that every value in an array is numerical and meaningful. So before training you have two basic choices: remove the incomplete data, or fill it in.
In Spark, both choices are methods on df.na, which returns a DataFrameNaFunctions object. Its drop method returns a new DataFrame without the rows that contain null or NaN values. Its fill method returns a new DataFrame with the null values replaced by a value you choose. Dropping is simple, but scikit-learn warns that it comes at the price of losing data which may be valuable, even when that data is incomplete. Its suggested alternative is to impute the missing values, which means inferring them from the known part of the data.
The simplest kind of imputation is univariate. scikit-learn defines it as filling values in one feature using only the non-missing values in that same feature. You summarise the column as one number (or one category), then write that value into every gap. This lesson covers the three summaries used for this: the mean, the median, and the mode (most frequent value).
Checkpoint 1 of 4· Check yourself
A univariate imputer fills missing values in column income. Which data does it use to compute the fill value?
Univariate imputation looks at a single feature. Using the other columns would make it multivariate imputation, which is a different technique.
“imputes values in the i-th feature dimension using only non-missing values in that feature dimension”Source: scikit-learn.org
2.Computing the mean, median, and mode in Spark
PySpark has an aggregate function for each of the three statistics. sf.mean(col) returns the average of the values in a group and is an alias of sf.avg. sf.median(col) returns the median. sf.mode(col) returns the most frequent value. Because they are aggregates, you can call them with select to get one value for the whole column, or with groupby(...).agg(...) to get one value per group.
import pyspark.sql.functions as sf
df = spark.createDataFrame([(1982, None), (1990, 2), (2000, 4)], ["birth", "age"])
df.select(sf.mean("age")).show()This is the behaviour imputation needs. The statistic is computed from the values the column actually has, and those are the values used to estimate the missing ones. sf.mode has one extra parameter, deterministic. When several values are tied for the highest frequency, Spark returns any one of them if deterministic is false or not set. If it is true, Spark returns the lowest. That matters when the fill value must be the same on every run.
from pyspark.sql import functions as sf
df = spark.createDataFrame([(-10,), (0,), (10,)], ["col"])
df.select(sf.mode("col", True)).show()| Statistic | PySpark function | scikit-learn SimpleImputer strategy | What it returns |
|---|---|---|---|
| Mean | sf.mean (alias of sf.avg) | 'mean' | Average of the non-null values |
| Median | sf.median | 'median' | Middle value of the non-null values |
| Mode | sf.mode | 'most_frequent' | Most frequent value. In Spark, ties depend on deterministic |
Checkpoint 2 of 4· Check yourself
You compute sf.mode("col") on a column where two values are tied for most frequent, and you don't pass deterministic. What does Spark guarantee?
deterministic defaults to false. In that case Spark may return any of the tied values. You only get the lowest one if you set deterministic=True.
“either any of values is returned if deterministic is false or is not defined”Source: docs.databricks.com
3.Which statistic fits which column
The first thing to look at is the column's type. You can't take the mean or median of a column of strings such as country codes or product tiers. Of the three statistics, only the most frequent value works for them. scikit-learn says this directly: SimpleImputer accepts categorical data, as strings or pandas categoricals, only with the 'most_frequent' or 'constant' strategy. Spark's sf.mode is just as general, because it returns the most frequent value of whatever the column holds.
from pyspark.sql import functions as sf
df = spark.createDataFrame([
("Java", 2012, 20000), ("dotNET", 2012, 5000),
("Java", 2012, 22000), ("dotNET", 2012, 10000),
("dotNET", 2013, 48000), ("Java", 2013, 30000)],
schema=("course", "year", "earnings"))
df.groupby("course").agg(sf.median("earnings")).show()The median is 10000, the value Spark reports. The mean is (5000 + 10000 + 48000) / 3 = 21000, which is higher than two of the three real values. The single 48000 pulls the mean upward but leaves the median unchanged. For Java (20000, 22000, 30000) the two are close: 24000 and 22000.
That arithmetic is the reason behind the usual rule for numeric columns. If the values are fairly symmetric, the mean and median are close and either one works. If a few extreme values stretch one tail, the mean moves toward them. The median stays with the bulk of the data, so it gives a more typical fill value. The Databricks and scikit-learn pages document how each statistic is computed, but they don't state a selection rule. The guidance here comes from what the example's numbers show, not from vendor documentation.
Checkpoint 3 of 4· 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.
Checkpoint 4 of 4· Check yourself
A string column membership_tier has nulls, and you want to impute it with scikit-learn's SimpleImputer. Which strategy can you use?
String and categorical data are supported only by the 'most_frequent' and 'constant' strategies. You can't average category labels.
“supports categorical data represented as string values or pandas categoricals when using the 'most_frequent' or 'constant' strategy”Source: scikit-learn.org
Exam traps
Each one states something that sounds right. Open it to see what is actually true.
1.When computing a column's mean to use as a fill value, the nulls count as zeros, so the mean comes out too low.Why is that wrong?
Spark's mean (avg) skips nulls. In the documented example, the ages None, 2 and 4 give avg(age) = 3.0, not 2.0.
2.sf.mode always returns the same value, so a mode-based fill can be reproduced without any extra setting.Why is that wrong?
When there is a tie, sf.mode returns any of the tied values unless deterministic is true. Only then does it consistently return the lowest.
3.A mean or median strategy can be applied to a string categorical column, as long as the imputer is configured correctly.Why is that wrong?
scikit-learn's SimpleImputer supports string or categorical data only with the 'most_frequent' or 'constant' strategies. For categories, use the mode.
Covered in Which statistic fits which column
Sources
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Returns a DataFrameNaFunctions for handling missing values.”
↩︎ Drop the row, or fill the gap? - 2.
“Returns a new DataFrame omitting rows with null or NaN values.”
↩︎ Drop the row, or fill the gap? - 3.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.”
↩︎ Drop the row, or fill the gap?“supports categorical data represented as string values or pandas categoricals when using the 'most_frequent' or 'constant' strategy”
↩︎ Which statistic fits which column“using the statistics (mean, median or most frequent) of each column in which the missing values are located”
↩︎ Key concept“supports categorical data represented as string values or pandas categoricals when using the 'most_frequent' or 'constant' strategy”
↩︎ Exam trap 3“imputes values in the i-th feature dimension using only non-missing values in that feature dimension”
↩︎ Checkpoint - 4.
“Returns the average of the values in a group. An alias of avg.”
↩︎ Computing the mean, median, and mode in Spark“Example 2: Calculating the average age with None”
↩︎ Exam trap 1“Example 2: Calculating the average age with None”
↩︎ Prediction - 5.
“Returns the median of the values in a group.”
↩︎ Computing the mean, median, and mode in Spark“Returns the median of the values in a group.”
↩︎ Which statistic fits which column - 6.
“Returns the most frequent value in a group.”
↩︎ Computing the mean, median, and mode in Spark“the lowest value is returned if deterministic is true”
↩︎ Exam trap 2“either any of values is returned if deterministic is false or is not defined”
↩︎ Checkpoint