CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 2 · Lesson 24/48

    Impute missing values with the mean, median or mode in Spark and scikit-learn

    Impute missing values with the mode, mean, or median value

    17 min read
    2.11% of exam
    12 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    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.

    Which statistic to fill with, by column
    ColumnFill withReason
    Numeric, roughly symmetricmeanThe average represents the centre well when nothing pulls it
    Numeric, skewed or with outliersmedianThe 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?

    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?

    Sources123

    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.

    sf.mean ignores the None row: the average of 2 and 4 is 3.0python
    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.

    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()

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

    Sources456738

    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.

    A numeric fill value only touches numeric columns: name and bool keep their nullspython
    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.

    What each form of na.fill touches on the example DataFrame
    CallColumns filledColumns left with NULL
    df.na.fill(50)age, heightname, bool
    df.na.fill(False)boolage, height, name
    df.na.fill({'age': 50, 'name': 'unknown'})age, nameheight, bool
    df.na.fill(value='Spark', subset='name')nameage, 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.

    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.

    fit learns column means (4 and 3.666) from one array; transform applies them to anotherpython
    >>> 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?

    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?

    Sources82

    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?

    Sources1011

    Sources

    (12)

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

    1. 2.
      “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
    2. 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
    3. 4.
      “Returns the average of the values in a group. An alias of avg.”
      ↩︎ Computing the mean, median and mode in Spark
    4. 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
    5. 7.
      “This method implements a variation of the Greenwald-Khanna algorithm with some speed optimizations.”
      ↩︎ Computing the mean, median and mode in Spark
    6. 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
    7. 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
    8. 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
    9. 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

    Ready to test yourself?

    Practise the 7 questions on this subdomain.

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