How do you handle missing data (nulls) in a PySpark DataFrame?
Source: PySpark documentation
First decide what null means for each column. Then use na.drop(subset=...) for rows you cannot use, na.fill({...}) or coalesce(col, default) for safe defaults, and when(col.isNull(), ...) for rules. Count nulls per column as a quality check, and never fill a business value like an amount silently.
Step 1: measure and decide
Missing data has different meanings: "unknown", "not applicable", "zero". Decide per column before changing anything. Count nulls first:
from pyspark.sql import functions as F
null_counts = df.select([
F.count(F.when(F.col(c).isNull(), c)).alias(c) for c in df.columns
])
null_counts.show()
F.count ignores nulls, so count(when(isNull, c)) counts only the null rows. For float/double columns also check F.isnan(c): NaN is a value, not null.
Step 2: choose a strategy
# Drop rows that cannot be used (only look at key columns)
clean = df.na.drop(subset=["order_id", "customer_id"]) # how="any" by default
# keep rows with at least 3 non-null values: df.na.drop(thresh=3)
# Fill with defaults per column (dict is explicit and safe)
filled = df.na.fill({"country": "unknown", "qty": 0})
# Fill from another column or expression
df.withColumn("city", F.coalesce("city", "billing_city", F.lit("unknown")))
# Apply a business rule
df.withColumn("status", F.when(F.col("amount").isNull(), "pending").otherwise("paid"))
Gotcha: fill skips columns of a different type
df.na.fill(0) # fills only numeric columns; string nulls stay null
df.na.fill("unknown") # fills only string columns; numeric nulls stay null
There is no error: columns whose type does not match the fill value are left unchanged. Use a dict per column, and check the result with a null count afterwards.
Nulls in joins and aggregates
- Joins:
null == nullis not true, so rows with null keys never match in an equality join. Use null-safe equalitya.eqNullSafe(b)(SQL<=>) when null should match null. - Aggregates:
sum,avg,min,max,count(col)ignore nulls;count("*")counts every row;sumof all-null is null. - Comparisons:
col > 5with null gives null, which afiltertreats as false, so null rows disappear. UseisNull()explicitly.
Rules of thumb
- Never fill a business measure (amount, price) with 0 silently: it changes totals. Prefer to flag, route to a quarantine table, or fill with a documented default.
- Keep a record of how many rows were dropped or filled and alert when the rate jumps.
- Fill categorical columns with a clear label like
unknown, not an empty string.
- 1Meaningwhat null means per column
- 2Countnulls per column as a DQ check
- 3Dropna.drop(subset=...) for unusable rows
- 4Fillna.fill or coalesce for safe defaults
- 5Ruleswhen(col.isNull(), ...)
See the concept: Spark shufflegroupBy moves every record to the partition that owns its key
Input partition 0
Input partition 1
Input partition 2
Stage 1: narrow transformations run in place
Key points
- Decide what null means per column, then measure null counts before changing data.
na.drop(subset=...),na.fill({...}),coalesceandwhen/otherwiseare the main tools.na.fill(value)silently skips columns whose type differs from the value.- NaN is not null; nulls never equal other nulls in joins unless you use
eqNullSafe. - Aggregates ignore nulls;
count("*")does not.
Common mistakes
- Using
na.fill(0)and assuming string columns were filled too. - Filling a numeric business value with 0 and corrupting totals.
- Forgetting NaN in float columns.
- Dropping rows with
na.drop()on all columns when only keys matter. - Expecting null keys to match in a join.
Prerequisites
- DataFrame basics
- Spark column expressions
Best practices
- Run per-column null counts as a data quality check on every load.
- Use explicit dictionaries for
fillandsubsetfordrop. - Log or quarantine dropped rows instead of discarding silently.
- Document the meaning of null for each important column.
Likely follow-ups
- What is the difference between null and NaN in Spark?
- How do you join on columns that may contain nulls?
- Why does
df.na.fill(0)not fill my string column? - How do aggregate functions treat null values?
- When should you drop rows with nulls and when should you impute?