Design a PySpark pipeline to identify and handle missing data in a distributed dataset across multiple columns.
Instruction: Explain your approach to identifying missing data in a distributed dataset using PySpark. Include how you would handle different data types (categorical vs numerical) and your strategy for either imputing or removing missing data based on the dataset's characteristics and the analysis goals.
Updated
Define what counts as missing for each field. SQL NULL, floating-point NaN, blank text and domain sentinel values are distinct representations; isNull() alone does not detect all of them. Count the chosen conditions in distributed aggregations and retain row-level flags before changing values.
This illustrative policy treats null/NaN measurements as missing, normalizes blank category strings, and learns a numeric mean from training rows only. It assumes an existing SparkSession named spark:
from pyspark.sql import functions as F
from pyspark.ml.feature import Imputer
raw = spark.createDataFrame([
(1, "train", 10.0, " A "),
(2, "train", None, " "),
(3, "train", 30.0, None),
(4, "test", float("nan"), "B"),
(5, "test", 1000.0, "B"),
], "id int, split string, value double, category string")
prepared = (raw
.withColumn("value_missing", F.col("value").isNull() | F.isnan("value"))
.withColumn("category", F.when(F.length(F.trim("category")) > 0,
F.trim("category")))
.withColumn("category_missing", F.col("category").isNull()))
counts = prepared.agg(
F.count(F.when(F.col("value_missing"), 1)).alias("value"),
F.count(F.when(F.col("category_missing"), 1)).alias("category")
).first()
assert (counts.value, counts.category) == (2, 2)
train = prepared.filter(F.col("split") == "train")
model = Imputer(inputCols=["value"], outputCols=["value_imputed"],
strategy="mean").fit(train)
clean = model.transform(prepared).fillna({"category": "[missing]"})
assert clean.filter("id = 4").first().value_imputed == 20.0
assert clean.filter("id = 5").first().value_imputed == 1000.0
assert clean.filter("id = 2").first().category_missing
The category marker must be reserved or accompanied by the retained flag so it cannot be confused with a real category. Imputer supports numeric columns; it is not a categorical imputer. An all-missing training column needs a deliberate fallback or rejection policy. Infinity and out-of-range measurements also need validation; they are not made valid by this missing-value rule. Imputer contract
Choose imputation, exclusion or explicit missingness based on the missing-data mechanism and intended use, not simply a normal-versus-skewed histogram rule. Fit learned preprocessing within training folds, report exclusions and preserve original fields/provenance. No imputation method guarantees unbiased estimates, and dropping a small fraction can still introduce selection bias.