CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 2 · Lesson 20/48

    Remove outliers from a Spark DataFrame with stddev bounds or IQR fences

    Remove outliers from a Spark DataFrame based on standard deviation or IQR

    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

    • Read the mean, standard deviation and quartiles of a column from a Spark summary and turn them into outlier bounds
    • Filter a Spark DataFrame to the rows within mean ± k·stddev, using avg/mean and stddev
    • Compute Q1 and Q3 with approxQuantile, derive the IQR, and keep rows inside Q1 − 1.5·IQR and Q3 + 1.5·IQR
    • Choose a relativeError for approxQuantile, or an accuracy for percentile_approx, and explain what it costs
    • Choose between standard-deviation bounds and IQR fences based on the shape of the distribution

    Key concept

    Outlier fence — An outlier fence is a lower and an upper cut-off calculated from a column's own statistics, either the mean ± k standard deviations or the quartiles widened by 1.5 interquartile ranges. Rows between the two fences are kept and rows outside them are dropped.

    1.Outlier bounds come from the column's own statistics

    An outlier is a row whose value sits so far from the rest of its column that it would distort a model trained on it. One sensor glitch reading 9,999, or one claim a thousand times larger than usual, can pull a regression line toward itself. Spark has no single "drop outliers" call. You calculate two numbers, a lower bound and an upper bound, and then keep only the rows that fall between them. The whole skill comes down to choosing which statistics to build those bounds from.

    There are two standard recipes, and each needs different inputs. Standard-deviation bounds need the mean and the standard deviation. IQR fences need the first quartile (25%) and the third quartile (75%). One profiling pass gives you all four: DataFrame.summary()/describe() and dbutils.data.summarize report count, mean, stddev, min, max and percentiles for each numeric column. summary() also accepts statistic names as arguments: count, mean, stddev, min, max, and approximate percentiles written as a percentage, such as "25%" and "75%". Called with no arguments it reports them all; called with names it reports only those.

    The mean, stddev, 25% and 75% rows of summary() are the inputs for both outlier methodspython
    df.select("age", "weight", "height").summary().show()
    # +-------+----+------------------+-----------------+
    # |summary| age|            weight|           height|
    # +-------+----+------------------+-----------------+
    # |  count|   3|                 3|                3|
    # |   mean|12.0| 40.73333333333333|            145.0|
    # | stddev| 1.0|3.1722757341273704|4.763402145525822|
    # |    min|  11|              37.8|            142.2|
    # |    25%|  11|              37.8|            142.2|
    # |    50%|  12|              40.3|            142.3|
    # |    75%|  13|              44.1|            150.5|
    # |    max|  13|              44.1|            150.5|
    # +-------+----+------------------+-----------------+

    Reading the bounds off a summary is fine for exploration, because summary() is meant for exploratory analysis and the schema of its result is not guaranteed to stay the same. A pipeline that drops outliers on every run should compute the statistics in code and use the values directly in a filter. The sections below do exactly that. One thing holds for every method here: null values are skipped when the statistics are computed, so a column with missing values still gets bounds built from its non-null rows.

    Checkpoint 1 of 8· Fill the gap

    You want only the inputs for IQR fences (the 25% and 75% quartiles) plus a few sanity statistics, in one profiling pass. Which method completes this call?

    df.select("age", "weight", "height"). ? ("count", "min", "25%", "75%", "max").show()
    # +-------+---+------+------+
    # |summary|age|weight|height|
    # +-------+---+------+------+
    # |  count|  3|     3|     3|
    # |    min| 11|  37.8| 142.2|
    # |    25%| 11|  37.8| 142.2|
    # |    75%| 13|  44.1| 150.5|
    # |    max| 13|  44.1| 150.5|
    # +-------+---+------+------+

    Sources12

    2.Standard-deviation bounds: keep rows within mean ± k·stddev

    The standard-deviation method keeps every row within k standard deviations of the mean. The usual choice is k = 3. For a column that is roughly normally distributed, a band that wide holds almost all ordinary values, so whatever falls outside it is unusual. A Databricks pipeline expectation uses the same pattern for a statistical range check, defining avg(amount) - 3 * stddev(amount) as the lower bound and avg(amount) + 3 * stddev(amount) as the upper bound.

    Both statistics are ordinary aggregate functions in pyspark.sql.functions. mean is an alias of avg, so code that uses either one computes the same number. stddev is an alias of stddev_samp, the sample standard deviation. Put both in a single select and call .first() to bring the one-row result back to the driver as plain Python numbers. df.agg(...) works just as well, because it aggregates the whole DataFrame without groups.

    stddev is a column aggregate, the same kind of expression as avg/meanpython
    import pyspark.sql.functions as sf
    spark.range(6).select(sf.stddev("id")).show()

    filter keeps the rows that satisfy its condition, so write the condition for the rows you want to keep. With stats = df.select(mean("reading").alias("m"), stddev("reading").alias("s")).first(), the cleaned DataFrame is df.filter((col("reading") >= stats["m"] - 3*stats["s"]) & (col("reading") <= stats["m"] + 3*stats["s"])). Two details go wrong in practice. Reversing the comparisons and joining them with | returns the complement: a DataFrame of only the outliers. That is handy for inspecting them, but it is the opposite of removing them. Dropping the multiplier (k = 1) narrows the band to a single standard deviation, which throws away a large share of perfectly ordinary readings along with the real outliers.

    Combine two Column conditions with & so that a row must satisfy bothpython
    df.filter((df.age > 3) & (df.subject == "Physics")).show()
    # +---+----+-------+
    # |age|name|subject|
    # +---+----+-------+
    # |  5| Bob|Physics|
    # +---+----+-------+

    Checkpoint 2 of 8· Check yourself

    Two teammates write the same 3-sigma filter for a reading column. Pipeline A computes its bounds from avg("reading") and stddev_samp("reading"). Pipeline B uses mean("reading") and stddev("reading"). Both use k = 3 and the same filter condition. How do the cleaned DataFrames compare?

    Checkpoint 3 of 8· Exam question

    A sensor readings DataFrame is approximately normally distributed, and the team wants to flag values more than three standard deviations from the mean as outliers before removing them from the reading column. Which Spark code correctly computes this filter?

    Sources34567

    3.IQR fences with approxQuantile

    The IQR method builds its fences from quartiles instead of the mean. The interquartile range is IQR = Q3 − Q1, the width of the middle half of the data. Any row below Q1 − 1.5·IQR or above Q3 + 1.5·IQR is an outlier. Spark computes the quartiles with DataFrame.approxQuantile(col, probabilities, relativeError), which is also available as df.stat.approxQuantile. Each probability is a float between 0 and 1: 0.0 is the minimum, 0.5 the median and 1.0 the maximum. For one column name you get back a list of floats, one per probability. Pass a list of column names and you get a list of lists, one for each column.

    approxQuantile on a single column returns a plain Python list of floats, one per requested probabilitypython
    data = [(1,), (2,), (3,), (4,), (5,)]
    df = spark.createDataFrame(data, ["values"])
    quantiles = df.approxQuantile("values", [0.0, 0.5, 1.0], 0.05)
    quantiles
    # [1.0, 3.0, 5.0]

    relativeError trades accuracy for cost. It is the relative target precision, and it must be 0 or greater. At 0, Spark computes exact quantiles, which can be very expensive on a large table. A small positive value such as 0.05 or 0.01 gives an approximate quartile far more cheaply. Values above 1 are accepted but behave the same as 1. The algorithm is a variation of Greenwald-Khanna, and it returns a value from the data whose rank is within the requested error of the exact rank. For outlier fences that is plenty, because the 1.5 multiplier is a rule of thumb rather than a precise boundary. When a team wants a fast job, it passes a positive tolerance, not 0.0.

    The complete IQR filter takes three steps:

    1. q1, q3 = df.approxQuantile("amount", [0.25, 0.75], 0.05) unpacks the two quartiles from the returned list.
    2. iqr = q3 - q1 gives the range. Subtracting in the other order produces a negative IQR, and every fence built from it lands in the wrong place.
    3. df.filter((col("amount") >= q1 - 1.5*iqr) & (col("amount") <= q3 + 1.5*iqr)) keeps the rows inside the fences. The lower fence is anchored to Q1 and the upper fence to Q3, never the other way round.

    Checkpoint 4 of 8· Check yourself

    A cleaning job unpacks the quartiles with q1, q3 = ... and then builds the fences from iqr = q3 - q1. Which call should go on the right-hand side so that the fences come out correct?

    Checkpoint 5 of 8· Exam question

    A data engineer needs to remove outliers from the amount column of a Spark DataFrame using the IQR method, using a relative error tolerance of 0.05 when computing quartiles to keep the job fast on a large dataset. Which code correctly implements this?

    Sources28

    4.percentile_approx: quartiles as a column expression

    approxQuantile is a DataFrame method that returns Python numbers right away. percentile_approx is the same calculation written as a column expression. pyspark.sql.functions.percentile_approx(col, percentage, accuracy=10000) returns a Column. You can put it in select or agg alongside other aggregates, or compute it per group with groupBy(...).agg(...). In SQL, percentile_approx and approx_percentile are synonyms, so you will see both names.

    percentile_approx returns the 25th, 50th and 75th percentiles as one array columnpython
    from pyspark.sql import functions as sf
    key = (sf.col("id") % 3).alias("key")
    value = (sf.randn(42) + key * 10).alias("value")
    df = spark.range(0, 1000, 1, 1).select(key, value)
    df.select(
        sf.percentile_approx("value", [0.25, 0.5, 0.75], 1000000)
    ).show(truncate=False)

    The precision setting runs in the opposite direction from relativeError. accuracy is a positive integer, and a higher value gives better accuracy at the cost of memory. The relative error is 1.0/accuracy. The default of 10000 therefore corresponds to a relative error of 0.0001, and the 1000000 in the example above asks for a far tighter estimate. Grouping is the case where percentile_approx clearly wins. When outliers must be judged within each store, region or sensor, one groupBy("key").agg(...) computes quartiles for every group in a single pass. With approxQuantile you would need a separate call per group.

    The two ways to get approximate quartiles in Spark
    AspectapproxQuantilepercentile_approx
    Called onA DataFrame (df.approxQuantile or df.stat.approxQuantile)A column, inside select or agg
    Precision parameterrelativeError, a float >= 0; 0 means exactaccuracy, a positive int (default 10000); relative error is 1.0/accuracy
    Higher setting meansCoarser, cheaper estimateFiner estimate, more memory
    ReturnsA Python list of floats (a list of lists for several columns)A Column holding the percentile, or an array for several percentages
    Per-group quartilesNot directly; one call per subsetYes, through groupBy(...).agg(...)

    Checkpoint 6 of 8· Match them up

    Each setup below computes quartiles for outlier fences. Match each setup to the result it produces.

    Tap a term, then the definition that fits it.

    Sources910

    5.Choosing between standard-deviation bounds and IQR fences

    Pick the method that matches the shape of the distribution. Standard-deviation bounds fit a column that is roughly normal and symmetric, such as sensor readings scattered around a set point. There, mean ± 3·stddev is a meaningful band and both statistics are cheap single-pass aggregates.

    For heavily skewed data, use IQR fences. Insurance claims, transaction amounts and household incomes are typical: most values are modest and a few are enormous. On such a column the standard-deviation method undermines itself. avg averages every value, including the extreme ones, and the standard deviation measures spread around that inflated mean. The largest claims pull the centre up and widen the band, so the upper bound moves out toward the very values it was supposed to catch. Q1 and Q3 describe the middle half of the data. A handful of huge claims barely moves them, so the fences stay anchored to the bulk of the distribution, and only values that are genuinely far from it fall outside.

    Removing outliers means filtering rows on a statistical boundary. Two look-alikes do something different. Capping replaces every value above a high percentile with that percentile's value. Every row stays in the DataFrame, so it does not remove anything. Dropping a fixed number of the highest and lowest rows after a sort ignores the data's spread entirely. It removes the same count whether the column has no outliers or hundreds of them. The two fence methods let the data decide which rows are extreme, and filter with a Boolean Column condition does the removal.

    Checkpoint 7 of 8· Check yourself

    A fraud model trains on a transaction-amount column. Most amounts are modest, and a handful are thousands of times larger. Which approach removes the outlier rows without the boundary being dragged toward those extreme amounts?

    Checkpoint 8 of 8· Exam question

    A dataset of insurance claim amounts is heavily right-skewed, with a small number of extremely large claims sitting far above the much smaller majority. The team wants to drop only genuine outliers before training a regression model, without letting those extreme claims distort where the outlier boundary itself gets drawn. Which approach to removing outliers from the Spark DataFrame best fits this situation?

    Sources117

    Sources

    (12)

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

    1. 1.
      “arbitrary approximate percentiles specified as a percentage (e.g., 75%).”
      ↩︎ Outlier bounds come from the column's own statistics
      “This function is meant for exploratory data analysis”
      ↩︎ Outlier bounds come from the column's own statistics
    2. 2.
      “Null values will be ignored in numerical columns before calculation.”
      ↩︎ Outlier bounds come from the column's own statistics
      “If set to zero, the exact quantiles are computed, which could be very expensive.”
      ↩︎ IQR fences with approxQuantile
      “Note that values greater than 1 are accepted but gives the same result as 1.”
      ↩︎ IQR fences with approxQuantile
      “If the input col is a string, the output is a list of floats.”
      ↩︎ IQR fences with approxQuantile
      “If set to zero, the exact quantiles are computed, which could be very expensive.”
      ↩︎ Exam trap 1
      “Each number must be a float in the range [0, 1]. For example 0.0 is the minimum, 0.5 is the median, 1.0 is the maximum.”
      ↩︎ Checkpoint
    3. 3.
      “avg(amount) - 3 * stddev(amount) as lower_bound,”
      ↩︎ Standard-deviation bounds: keep rows within mean ± k·stddev
      “avg(amount) - 3 * stddev(amount) as lower_bound,”
      ↩︎ Key concept
    4. 5.
      “Returns the average of the values in a group. An alias of avg.”
      ↩︎ Standard-deviation bounds: keep rows within mean ± k·stddev
      “Returns the average of the values in a group. An alias of avg.”
      ↩︎ Exam trap 3
    5. 6.
      “Aggregate on the entire DataFrame without groups (shorthand for df.groupBy().agg()).”
      ↩︎ Standard-deviation bounds: keep rows within mean ± k·stddev
    6. 7.
      “DataFrame: A new DataFrame with rows that satisfy the condition.”
      ↩︎ Standard-deviation bounds: keep rows within mean ± k·stddev
      “A Column of BooleanType or a string of SQL expressions.”
      ↩︎ Choosing between standard-deviation bounds and IQR fences
      “DataFrame: A new DataFrame with rows that satisfy the condition.”
      ↩︎ Exam trap 2
    7. 8.
      “This method implements a variation of the Greenwald-Khanna algorithm with some speed optimizations.”
      ↩︎ IQR fences with approxQuantile
    8. 9.
      “Higher value yields better accuracy. 1.0/accuracy is the relative error (default: 10000).”
      ↩︎ percentile_approx: quartiles as a column expression
      “Higher value yields better accuracy. 1.0/accuracy is the relative error (default: 10000).”
      ↩︎ Exam trap 4

    Also cited

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