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.
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|
# +-------+---+------+------+summary() takes statistic names as arguments, including approximate percentiles requested by name, such as "25%" and "75%". Those two quartiles are the inputs that IQR fences are built from. The other methods do not take a list of statistic names with percentiles like this.
Source: docs.databricks.com2.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.
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.
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?
stddev is an alias of stddev_samp (the sample standard deviation), and mean is an alias of avg. Both pipelines therefore produce the same mean and standard deviation, the same mean ± 3·stddev bounds and the same filtered rows. Both aggregates also skip nulls.
“Alias for stddev_samp.”Source: docs.databricks.com
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?
Correct answer: A — stats = df.select(mean("reading").alias("m"), stddev("reading").alias("s")).first()
df.filter((col("reading") >= stats["m"] - 3*stats["s"]) & (col("reading") <= stats["m"] + 3*stats["s"]))
- A. The mean and standard deviation are computed once, and the filter keeps rows within three standard deviations on either side, matching the requested three-sigma threshold exactly.
- B. This filters to within one standard deviation rather than three, which is a far tighter band that flags a large share of ordinary sensor readings as outliers instead of only the extreme ones.
- C. This mixes a quartile-based IQR calculation with the requested standard-deviation threshold, which is a different outlier method entirely and does not measure distance from the mean in standard deviations.
- D. The comparison operators and the
|combine to keep only rows outside the three-standard-deviation band, which retains the outliers themselves rather than removing them from the DataFrame.
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.
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:
q1, q3 = df.approxQuantile("amount", [0.25, 0.75], 0.05)unpacks the two quartiles from the returned list.iqr = q3 - q1gives the range. Subtracting in the other order produces a negative IQR, and every fence built from it lands in the wrong place.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?
approxQuantile takes probabilities as floats between 0 and 1, so the quartiles are 0.25 and 0.75. The "25%" names belong to summary(), not to this call. The values come back in the order you asked for them, so [0.75, 0.25] would put Q3 into q1 and give a negative IQR.
“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.”Source: docs.databricks.com
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?
Correct answer: A — q1, q3 = df.approxQuantile("amount", [0.25, 0.75], 0.05)
iqr = q3 - q1
df.filter((col("amount") >= q1 - 1.5*iqr) & (col("amount") <= q3 + 1.5*iqr))
- A. Passing
0.05as the relative error gives Spark the requested approximation tolerance, and the IQR is correctly computed asq3 - q1before building the standard lower and upper fences from it. - B. Passing
0.0forces Spark to compute the exact quantiles instead of the requested0.05tolerance, which requires a far more expensive full pass over the data and defeats the goal of keeping the job fast. - C. This computes the mean and standard deviation instead of quartiles, which is the standard-deviation outlier method rather than the IQR method the task specifically asked for, and it ignores the relative error tolerance entirely.
- D. The IQR is computed as
q1 - q3instead ofq3 - q1, producing a negative value that inverts the fence calculation and leaves the filter with nonsensical, backwards bounds.
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.
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.
| Aspect | approxQuantile | percentile_approx |
|---|---|---|
| Called on | A DataFrame (df.approxQuantile or df.stat.approxQuantile) | A column, inside select or agg |
| Precision parameter | relativeError, a float >= 0; 0 means exact | accuracy, a positive int (default 10000); relative error is 1.0/accuracy |
| Higher setting means | Coarser, cheaper estimate | Finer estimate, more memory |
| Returns | A Python list of floats (a list of lists for several columns) | A Column holding the percentile, or an array for several percentages |
| Per-group quartiles | Not directly; one call per subset | Yes, 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.
The two precision settings run in opposite directions. A relativeError of 0 asks approxQuantile for exact quantiles, and a small positive value keeps it cheap. For percentile_approx, a higher accuracy gives a finer estimate and costs more memory. Because percentile_approx is a column expression, it can go inside groupBy(...).agg(...) to get quartiles for each group.
“A positive numeric literal which controls approximation accuracy at the cost of memory. Higher value yields better accuracy.”Source: docs.databricks.com
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?
avg averages every value, extremes included, so on skewed data the mean and stddev grow and the upper bound moves out toward the outliers. The quartiles describe the middle half of the data and barely move, so IQR fences stay with the bulk of the values. Capping keeps every row, so it removes nothing. A one-stddev band throws away many ordinary values.
“Returns the average of the values in a group.”Source: docs.databricks.com
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?
Correct answer: A — Use approxQuantile to compute the first and third quartiles, derive the interquartile range, and filter out rows outside Q1 - 1.5*IQR and Q3 + 1.5*IQR, since quartile-based fences stay anchored to the bulk of the distribution.
- A. Interquartile fences are built from the 25th and 75th percentiles, which sit inside the bulk of the distribution and barely move even when a handful of claims are extremely large, so the outlier boundary stays stable on skewed data.
- B. Extreme values in a right-skewed column inflate both the mean and the standard deviation, which pushes the mean-plus-three-standard-deviations boundary far to the right and lets many genuine outliers slip through unflagged.
- C. Dropping a fixed count from each end assumes the true outlier fraction is constant across every dataset, which has no connection to where this particular skewed distribution's genuine outliers actually begin.
- D. Capping values at a percentile changes the data through winsorization rather than removing the affected rows, and it does not use the standard-deviation or IQR fences the task calls for at all.
Sources
(12)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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“summary(*statistics: str)”
↩︎ Outlier bounds come from the column's own statistics - 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.
“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.
“Alias for stddev_samp.”
↩︎ Standard-deviation bounds: keep rows within mean ± k·stddev - 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 - 6.
“Aggregate on the entire DataFrame without groups (shorthand for df.groupBy().agg()).”
↩︎ Standard-deviation bounds: keep rows within mean ± k·stddev - 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 - 8.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframestatfunctions/approxQuantileOfficial docs
“This method implements a variation of the Greenwald-Khanna algorithm with some speed optimizations.”
↩︎ IQR fences with approxQuantile - 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 - 10.
“This function is a synonym for approx_percentile aggregate function.”
↩︎ percentile_approx: quartiles as a column expression - 11.
“Returns the average of the values in a group.”
↩︎ Choosing between standard-deviation bounds and IQR fences
Also cited
“A positive numeric literal which controls approximation accuracy at the cost of memory. Higher value yields better accuracy.”
↩︎ Checkpoint