CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 2 · Lesson 23/48

    Mean vs median vs mode imputation for missing values

    Compare and contrast imputing missing values with the mean or median or mode value

    16 min read
    2.11% of exam
    8 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    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.

    na.drop() removes every row that contains a null, so one missing height costs a whole recordpython
    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|
    +---+------+-----+

    Sources12

    2.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.

    mean (an alias of avg) ignores the null row and averages only the known valuespython
    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?

    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?

    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.

    approxQuantile at probability 0.5 returns the median and skips the null rowspython
    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?

    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?

    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.

    mode ignores NULLs, works on any comparable type, and picks arbitrarily when frequencies tiesql
    > 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);
     1

    Ties 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.

    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|
    +---------------------------------------+

    Checkpoint 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?

    Sources562

    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.

    Drop, mean, median and mode compared by the column they suit
    StrategyColumn it suitsSpark computationWhere it goes wrong
    Drop rowsFew affected rows that you can sparena.drop()Removes the whole row, including every valid value in its other columns
    MeanNumeric, roughly symmetric, no extreme valuesavg / meanOne extreme value or a long tail pulls it away from the typical row
    MedianNumeric, skewed or outlier-heavyapproxQuantile with probability 0.5Adds nothing over the mean on symmetric data; exact computation (relativeError 0) is expensive
    ModeCategorical labelsmodePicks 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.

    A scalar fill writes the same 50 into every numeric column and leaves the string column nullpython
    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|
    # +---+------+-----+----+

    Sources78

    Sources

    (8)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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. 2.
      “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. 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. 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. 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. 6.
      “If there are multiple equally-frequent results then return the lowest (defaults to false).”
      ↩︎ Mode imputation for categorical columns
    7. 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. 8.
      “DataFrame.fillna and DataFrameNaFunctions.fill are aliases of each other.”
      ↩︎ Choosing a statistic per column and applying it

    Spotted a mistake, or was something unclear? Tell us.