Sub topic 11
Nulls and duplicates
This chapter assumes you can create a DataFrame, use withColumn and filter, and know that transformations are lazy. It covers how Spark treats missing values and repeated rows, and the mistakes that follow from each.
How nulls behave
A null means "value unknown". Spark follows SQL rules for it. Any comparison with null returns null, not true or false, and filter keeps only rows where the condition is true. So null rows disappear from both == x and != x filters.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders.filter(F.col("amount") != 30.0).show() # carol's null rows are missing
orders.filter(F.col("amount").isNull()).show() # the correct null test
orders.filter(F.col("amount").isNotNull()).show()Never write amount == None in a condition. Use isNull() and isNotNull().
Replacing or dropping nulls
Three tools cover most cases.
| Tool | What it does |
|---|---|
| `df.na.drop(subset=["amount"])` | Removes rows with nulls in the listed columns. |
| `df.na.fill({"amount": 0.0})` | Replaces nulls with a fixed value per column. |
| `F.coalesce("a", "b", F.lit(0))` | Returns the first non-null value, row by row. |
clean = orders.na.drop(subset=["amount"])
filled = orders.na.fill({"amount": 0.0})
with_default = orders.withColumn("amount_safe", F.coalesce("amount", F.lit(0.0)))Choose deliberately. Filling with 0 changes averages, because avg skips nulls but counts zeros. Dropping rows changes counts. Keep the null if "unknown" is the true answer.
Removing duplicates
distinct() removes rows that are identical in every column. dropDuplicates(subset) compares only the listed columns and keeps one arbitrary row from each group.
orders.distinct().show() # drops the repeated order 4
orders.dropDuplicates(["order_id"]).show() # one row per order_idWith a subset, "arbitrary" matters. If you need the latest row per key, do not rely on dropDuplicates. Rank rows with a window function (covered later) and keep rank 1.
Duplicates need a shuffle, so on large data they cost more than a simple filter.
Common errors
- Comparing with
Noneor"null"instead of usingisNull(). - Filling nulls before aggregating, which silently shifts averages.
- Using
dropDuplicateson a subset and assuming it keeps the newest row. - Forgetting that
count("*")counts null rows, whilecount("amount")does not.
Exercise
A DataFrame has an amount column with values 10, 20 and null. What does avg("amount") return, and what does it return after na.fill({"amount": 0})?
Show answer
Before filling, avg skips the null and returns 15.0 (30 / 2). After filling, the three values are 10, 20 and 0, so avg returns 10.0 (30 / 3). Filling changed the result.
Exercise
Why does orders.filter(F.col("amount") != 30.0) not return carol's rows, which have a null amount?
Show answer
Comparing null with 30.0 gives null, not true. filter keeps only rows where the condition is true, so the null rows are dropped. Add | F.col("amount").isNull() to keep them.