Describe a strategy to use PySpark for detecting outliers in a distributed dataset.
Instruction: Explain the methods you would use for identifying and handling outliers in large-scale data.
Updated
Use outlier rules to flag records for investigation, not to declare them errors automatically. Choose a reference population and a domain-appropriate feature scale; a global fence can mislabel a legitimate subgroup or seasonal regime. Mean/standard-deviation thresholds are not automatically preferable for highly skewed data.
This complete example requires a DoubleType value column and an existing session named spark. It keeps invalid values separate and uses an explicit finite magnitude limit so fence arithmetic stays finite:
import math
from pyspark.sql import functions as F
from pyspark.sql.types import DoubleType
def flag_iqr(data):
if not isinstance(data.schema["value"].dataType, DoubleType):
raise TypeError("value must be a DoubleType column")
x = F.col("value")
eligible = x.isNotNull() & ~F.isnan(x) & (F.abs(x) <= 1e100)
reference = data.filter(eligible)
quartiles = reference.approxQuantile("value", [0.25, 0.75], 0.01)
if len(quartiles) != 2:
raise ValueError("No eligible reference observations")
q1, q3 = quartiles
spread = q3 - q1
low, high = q1 - 1.5 * spread, q3 + 1.5 * spread
if not all(math.isfinite(v) for v in (low, high)):
raise ValueError("Nonfinite IQR fences")
flagged = data.withColumn("status", F.when(~eligible, "invalid")
.when((x < low) | (x > high), "flag").otherwise("within_fence"))
return flagged, (low, high)
data = spark.createDataFrame([(float(x),) for x in [1, 2, 2, 3, 4, 100]] +
[(None,), (float("nan"),), (float("inf"),)], "value double")
flagged, bounds = flag_iqr(data)
assert bounds == (-1.0, 7.0)
assert [r.value for r in flagged.filter("status = 'flag'").collect()] == [100.0]
assert flagged.filter("status = 'invalid'").count() == 3
The magnitude cap is a declared example domain, not a universal data-cleaning rule. Spark's approximation parameter bounds rank error, not numeric distance from a true quartile. Setting it to zero requests exact quantiles but can be expensive; document the selected approximation and examine threshold sensitivity. Quantile conventions also differ across software.
Zero IQR produces coincident fences; decide whether this is useful for the domain rather than dividing by zero or silently discarding the group. For predictive use, fit thresholds on training/reference data and apply fixed thresholds to later data instead of refitting on the evaluation set.
Preserve source values, reason counts and the policy version. Investigate flagged records, compare downstream results with/without justified corrections and retain an audit trail. Repartitioning is not inherently required for a global quantile/filter operation; optimize only after measuring its actual plan and resource use.