What you will be able to do
- Decide whether to drop rows with missing values or fill them, and say what each choice costs
- Choose mean imputation for symmetric numeric columns with no extreme values
- Explain why one extreme value drags the mean but not the median, and choose median imputation for skewed or outlier-heavy columns
- Choose mode imputation for categorical columns and describe how the mode behaves with ties and nulls
- Apply a different fill value to each column with na.fill and predict which columns a scalar fill leaves untouched
Key concept
Central-tendency imputation — You replace every missing value in a column with one statistic computed from that column's non-missing values: the mean, the median or the most frequent value. Which statistic is right depends on the column's type and on the shape of its distribution.
1.Dropping rows versus filling the gaps
A column with missing values forces a choice before training starts: remove the incomplete records, or fill each gap with a value taken from the rest of the column. Doing nothing usually isn't an option. scikit-learn estimators, for example, assume every value in the array is numeric and meaningful, so a blank or NaN breaks them.
Dropping is the blunter of the two tools. In Spark, df.na.drop() returns a new DataFrame without the rows that hold a null or NaN. Called with no arguments, as in the example below, a single null anywhere in a row is enough to remove the whole row. Bob's row had a valid age and name, but it was dropped because height was null. Tom's row was dropped too. Two of the three records are gone, along with every valid value they held.
from pyspark.sql import Row
df = spark.createDataFrame([
Row(age=10, height=80.0, name="Alice"),
Row(age=5, height=None, name="Bob"),
Row(age=None, height=None, name="Tom"),
])
df.na.drop().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 10| 80.0|Alice|
+---+------+-----+Filling, or imputation, keeps every row and infers each missing value from the known part of the data. The price of dropping is the data that came with the null. When 6% of rows lack one feature, dropping them throws away 6% of the training set plus every good value those rows held in their other columns. Dropping fits best when only a handful of rows are affected and they really are expendable. In every other case, the decision that matters is which value to fill with.
Checkpoint 1 of 8· Fill the gap
Bob has a valid age and name but no height, and Tom has neither age nor height. Which DataFrameNaFunctions method turns these three rows into the output shown, where only Alice's row is left?
from pyspark.sql import Row
df = spark.createDataFrame([
Row(age=10, height=80.0, name="Alice"),
Row(age=5, height=None, name="Bob"),
Row(age=None, height=None, name="Tom"),
])
df.na. ? ().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 10| 80.0|Alice|
+---+------+-----+Called with no arguments, na.drop() removes every row that holds a null. Bob's row goes because of one missing height, and his valid age and name go with it. A fill would keep all three rows and put a value in each gap, so there is nothing neutral about dropping.
Source: docs.databricks.com2.Mean imputation for symmetric numeric columns
The mean is the right fill for a numeric column whose values cluster symmetrically around a centre, with no extreme values. Think of a manufactured part's weight in grams, with a bell-shaped histogram. In that shape the average sits where most of the values are, so it represents a typical part well.
In Spark the mean is the aggregate avg, and mean is an alias for it. Nulls play no part in the calculation. The example below averages the two known ages, 2 and 4, returns 3.0 and ignores the row whose age is None. So the fill value comes only from the measurements you actually have, and the gaps don't distort it.
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|
+--------+On a symmetric column with no outliers, the median adds nothing. The mean and the median land in roughly the same place, and the median's robustness only matters when there are extremes to resist. So the median isn't automatically the safer choice. On a well-behaved column the mean is the standard default. The mode is the weak option here. When weights are recorded to fractions of a gram, few values repeat exactly, so the most frequent weight may be a rounding accident rather than a typical part.
Checkpoint 2 of 8· Check yourself
A part-weight column has a bell-shaped spread and these values: 10, 20, null, 30. You compute sf.mean on the column and use the result to fill the gap. Which value goes into the null row?
Spark's mean (an alias of avg) skips nulls and averages only the known values: (10 + 20 + 30) / 3 = 20.0. The fill value therefore comes only from real measurements. On a symmetric column with no outliers, that mean is the standard default.
“imputes values in the i-th feature dimension using only non-missing values in that feature dimension”Source: scikit-learn.org
Checkpoint 3 of 8· Exam question
A quality-control dataset tracks part_weight_grams for a manufactured component. Histograms show the distribution is approximately symmetric and bell-shaped, with no extreme outliers, and 3% of measurements are missing due to a sensor glitch. Which imputation strategy is the most defensible default for this column?
Correct answer: A — Impute the missing weights with the column mean, because a roughly symmetric distribution with no outliers lets the average represent the typical part weight accurately.
- A. The mean is appropriate here because a symmetric, outlier-free distribution means the average and the typical value coincide, so mean imputation does not introduce the bias it would on skewed data.
- B. The median is a safer default only when skew or outliers are present; on a symmetric outlier-free distribution it offers no advantage over the mean and is not the best-fit choice.
- C. The mode fits categorical or discrete data with a clearly repeated value, not a continuous physical measurement where most recorded weights are distinct.
- D. A fixed specification value ignores the actual observed distribution of part weights and is not one of the three statistics the scenario is asking to compare.
Sources3
3.Median imputation for skewed or outlier-heavy columns
The median depends on rank, not on magnitude, and that is why it wins on skewed columns. It is the 0.5 quantile: the value halfway through the sorted column. The largest value can grow from 5 to 1,000 to 1,000,000 and the middle of 2, 3, 4, 5 and that value is still 4. The mean of the same five values is 202.8. If you fill a missing days_since_last_login with 202.8, you tell the model that this customer has been gone for over six months. None of the active customers looks like that.
Outliers are values beyond standard-deviation bounds or the 1.5×IQR fences, as taught in Outliers: standard-deviation bounds and 1.5×IQR fences. For imputation, what matters is that one extreme value drags the mean and leaves the median almost where it was. A right-skewed column does the same thing with no single dramatic point: a long tail of large values pulls the mean above where most rows sit. Use the median in both cases. It describes the typical row, not the tail.
In Spark you compute the median with approxQuantile and the probability 0.5. As with the mean, nulls are dropped before the calculation, so the example below takes the median of 1, 3 and 4 and gets 3.0. The relativeError argument trades precision for cost. Setting it to zero computes the exact quantile, which can be very expensive on a large table. A small positive value returns an approximate median that's close enough for a fill value.
data = [(1,), (None,), (3,), (4,), (None,)]
df = spark.createDataFrame(data, ["values"])
df.stat.approxQuantile("values", [0.0, 0.5, 1.0], 0.05)
# [1.0, 3.0, 4.0]Checkpoint 4 of 8· Check yourself
In an orders table, most purchase amounts fall between 20 and 60, but a long tail of bulk orders reaches 50,000. Some amounts are null. Which expression should you use to compute the fill value for this column?
The long tail of bulk orders pulls the mean above where most orders sit. The median depends on rank, so it stays with the typical row. approxQuantile takes the probabilities as its second argument, so 0.5 there gives the median, and a small relativeError such as 0.01 keeps the calculation cheap.
“For example 0.0 is the minimum, 0.5 is the median, 1.0 is the maximum.”Source: docs.databricks.com
Checkpoint 5 of 8· Exam question
A retention analytics table includes days_since_last_login, a right-skewed numeric column where most customers log in within a week but a small group of dormant accounts push values into the thousands. About 6% of rows are missing this value, and the team wants to fill the gaps without letting the dormant-account outliers distort the typical customer's imputed value. Which imputation strategy best fits this column?
Correct answer: B — Impute the missing values with the column median, because the middle ranked login gap reflects a typical customer without being pulled toward the dormant-account extremes.
- A. The mean is pulled toward the extreme dormant-account values in a right-skewed distribution, so it overstates the typical customer's login gap rather than representing it accurately.
- B. The median is the correct choice here because it is robust to the extreme values from dormant accounts and represents the typical customer's login gap without distortion.
- C. The mode is intended for categorical or discrete data with a clearly repeated value; a continuous, mostly-unique login-gap column rarely has a meaningful most-frequent value to impute with.
- D. Dropping 6% of rows discards usable records and does not answer the question of which of the three imputation strategies fits a skewed numeric column.
Sources4
4.Mode imputation for categorical columns
A categorical column has no average and no middle value. Take shipping_method, with the values "Standard", "Express" and "Overnight". The mean and the median need numbers with a meaningful order. Even after the labels become numeric indices for encoding, averaging index 0 and index 2 gives 1. That points at whichever category the encoder happened to number 1, not at anything customers chose.
The mode is the most frequent non-null value in the column, so it always returns a label that already exists there. The result has the same type as the column, so the mode of a string column is a string that can go straight back into it. NULLs never win the count. In the first query below, three NULLs sit next to two 3s and the mode is still 3. A group that contains only nulls returns NULL.
> SELECT mode(col) FROM VALUES (NULL), (1), (NULL), (2), (NULL), (3), (3) AS tab(col);
3
> SELECT mode(col) FROM VALUES (array(1, 2)), (array(1, 2)), (array(2, 3)) AS tab(col);
[1, 2]
-- The function returns either 1 or 2, but not 3
> SELECT mode(col) FROM VALUES (1), (1), (2), (2), (3) AS tab(col);
1Ties make the mode non-deterministic. If "Standard" and "Express" are equally common, two runs over the same data can fill the gaps with different labels. Setting the deterministic argument to true resolves ties to the lowest value. In PySpark that is sf.mode(col, deterministic=True), and it defaults to false. In Databricks SQL the argument is available in Databricks Runtime 14.1 and above.
The mode reuses the category that occurs most often, so the column keeps the same set of labels it already had. A constant adds a category the column never contained, and the encoder later treats it as one more real level of the feature.
Checkpoint 6 of 8· Fill the gap
Three values each appear once, so all three tie for most frequent. Which second argument to sf.mode makes this query return -10 on every run, not just on some runs?
from pyspark.sql import functions as sf
df = spark.createDataFrame([(-10,), (0,), (10,)], ["col"])
df.select(sf.mode("col", ? )).show()
+---------------------------------------+
|mode() WITHIN GROUP (ORDER BY col DESC)|
+---------------------------------------+
| -10|
+---------------------------------------+When values tie, mode can return any of them unless deterministic is true. With deterministic set to true, it returns the lowest value, -10. False is the default and gives the non-deterministic behaviour, so repeated runs could impute different values.
Source: docs.databricks.comCheckpoint 7 of 8· Exam question
An order table has a shipping_method column with categorical values such as "Standard", "Express", and "Overnight". About 8% of rows are missing this value before the team one-hot encodes the feature for a classification model. Which imputation approach is most appropriate for this nominal categorical column?
Correct answer: A — Impute the missing shipping method with the mode, because replacing gaps with the category customers choose most often keeps the feature a valid, existing label.
- A. The mode is correct for a nominal categorical column because it fills gaps with an actual, already-observed category rather than a value with no meaning for labels.
- B. A mean requires arithmetic on the values, and shipping method categories have no inherent numeric order, so averaging category codes produces a meaningless result.
- C. A median requires the values to be ordered, and shipping method labels are nominal with no natural ranking, so a middle value is not well defined.
- D. Introducing a new placeholder category is a different technique from imputing with mean, median, or mode, and it changes the feature's cardinality rather than reusing an observed category.
5.Choosing a statistic per column and applying it
Choose the statistic one column at a time. Decide by the column's type first, then by its shape. A table often has a symmetric measurement, a skewed count and a nominal label side by side, and each one needs a different fill.
| Strategy | Column it suits | Spark computation | Where it goes wrong |
|---|---|---|---|
| Drop rows | Few affected rows that you can spare | na.drop() | Removes the whole row, including every valid value in its other columns |
| Mean | Numeric, roughly symmetric, no extreme values | avg / mean | One extreme value or a long tail pulls it away from the typical row |
| Median | Numeric, skewed or outlier-heavy | approxQuantile with probability 0.5 | Adds nothing over the mean on symmetric data; exact computation (relativeError 0) is expensive |
| Mode | Categorical labels | mode | Picks arbitrarily between tied labels unless deterministic is true; weak for continuous values that rarely repeat |
Once you've computed the statistics, na.fill writes them in. fillna is an alias of the same method. Pass it a dict that maps each column name to its own fill value: the median for the login gap, the mode for the shipping method, and so on. When you pass a dict, the subset argument is ignored. Passing a single scalar is a different operation, and it's the wrong one for imputation.
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|
# +---+------+-----+----+The scalar fill above makes two mistakes. First, age and height both got 50, a number that is no column's own statistic. Second, name and bool still contain NULL, because a fill value only reaches columns whose data type matches it. A string mode passed as a scalar would likewise skip every numeric column. If a column still holds nulls after a fill, check whether the fill value's type matched that column.
Checkpoint 8 of 8· Fill the gap
Before this call, age, height, name and bool all contain nulls. Afterwards, the numeric gaps hold 50 while name and bool still show NULL. Which fill value produced this output?
df.na.fill( ? ).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|
# +---+------+-----+----+A scalar fill only reaches columns whose data type matches it. The numeric 50 fills both age and height but skips the string and boolean columns, so their nulls stay. A dict would have filled name with 'unknown' and left height null, so for imputation you pass a dict with each column's own statistic.
Source: docs.databricks.comSources
(8)
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.”
↩︎ Dropping rows versus filling the gaps“Returns a new DataFrame omitting rows with null or NaN values.”
↩︎ Exam trap 2 - 2.https://scikit-learn.org/stable/modules/impute.htmlSecondary source
“However, this comes at the price of losing data which may be valuable (even though incomplete).”
↩︎ Dropping rows versus filling the gaps“A better strategy is to impute the missing values, i.e., to infer them from the known part of the data.”
↩︎ Dropping rows versus filling the gaps“when using the 'most_frequent' or 'constant' strategy”
↩︎ Mode imputation for categorical columns“using the statistics (mean, median or most frequent) of each column in which the missing values are located”
↩︎ Key concept“imputes values in the i-th feature dimension using only non-missing values in that feature dimension”
↩︎ Checkpoint - 3.
“Returns the average of the values in a group. An alias of avg.”
↩︎ Mean imputation for symmetric numeric columns“Returns the average of the values in a group. An alias of avg.”
↩︎ Exam trap 1 - 4.
“For example 0.0 is the minimum, 0.5 is the median, 1.0 is the maximum.”
↩︎ Median imputation for skewed or outlier-heavy columns“Null values will be ignored in numerical columns before calculation.”
↩︎ Median imputation for skewed or outlier-heavy columns“If set to zero, the exact quantiles are computed, which could be very expensive.”
↩︎ Median imputation for skewed or outlier-heavy columns - 5.
“Returns the most frequent, not NULL, value of expr in a group.”
↩︎ Mode imputation for categorical columns“The result type matches the type of the argument.”
↩︎ Mode imputation for categorical columns“If the group contains only nulls, the function returns NULL.”
↩︎ Mode imputation for categorical columns“The result is non-deterministic if there is a tie for the most frequent value.”
↩︎ Exam trap 3 - 6.
“If there are multiple equally-frequent results then return the lowest (defaults to false).”
↩︎ Mode imputation for categorical columns - 7.
“If a dict is provided, subset is ignored and value must be a mapping from column name to replacement value.”
↩︎ Choosing a statistic per column and applying it“Columns in subset that do not have a matching data type for value are ignored.”
↩︎ Choosing a statistic per column and applying it“Columns in subset that do not have a matching data type for value are ignored.”
↩︎ Exam trap 4 - 8.
“DataFrame.fillna and DataFrameNaFunctions.fill are aliases of each other.”
↩︎ Choosing a statistic per column and applying it