Skip to main content
Intermediatehow it works Verified ~8 min

How do you handle missing data (nulls) in a PySpark DataFrame?

Source: PySpark documentation

Quick answer

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:

main.py
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

main.py
# 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

main.py
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 == null is not true, so rows with null keys never match in an equality join. Use null-safe equality a.eqNullSafe(b) (SQL <=>) when null should match null.
  • Aggregates: sum, avg, min, max, count(col) ignore nulls; count("*") counts every row; sum of all-null is null.
  • Comparisons: col > 5 with null gives null, which a filter treats as false, so null rows disappear. Use isNull() 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.
Animated explanation
  1. 1Meaningwhat null means per column
  2. 2Countnulls per column as a DQ check
  3. 3Dropna.drop(subset=...) for unusable rows
  4. 4Fillna.fill or coalesce for safe defaults
  5. 5Ruleswhen(col.isNull(), ...)
Never silently fill a business value such as an amount.
See the concept: Spark shufflegroupBy moves every record to the partition that owns its key
Spark shuffle: groupBy(key)
key A key B key C

Input partition 0

ACBA

Input partition 1

BBCA

Input partition 2

CABC

Stage 1: narrow transformations run in place

Before: each input partition holds a mix of keys. After the shuffle, all records with the same key live in one partition. That data movement over the network is what makes wide transformations expensive.

Key points

  • Decide what null means per column, then measure null counts before changing data.
  • na.drop(subset=...), na.fill({...}), coalesce and when/otherwise are 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 fill and subset for drop.
  • 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?

References

Discussion