Sub topic 11
Nulls and duplicates
This chapter assumes you can already read a DataFrame, use select, filter and withColumn, and run groupBy aggregations in a Databricks notebook. Real data often has missing values and repeated rows. Spark handles both in ways that can surprise you, so this chapter covers how to detect them, handle them, and avoid silent mistakes.
How Spark represents missing values
A missing value in a Spark column is null. It is not an empty string, not zero, and not NaN. Every data type can hold a null unless the schema marks the column as non-nullable. For floating-point columns, NaN is a separate value. isNull() does not match NaN, so check both when you clean a double column from an outside source.
The examples below use a small orders DataFrame. It has one null amount, one null customer, and one pair of rows that repeat the same order under different ids.
from pyspark.sql import functions as F
from pyspark.sql import Window
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),
(5, "alice", "2024-02-10", 30.0),
(6, None, "2024-03-01", 10.0),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
).withColumn("order_date", F.to_date("order_date"))Finding nulls
Use isNull() and isNotNull() on a column. Never write col == None or col == F.lit(None). Those expressions evaluate to null for every row, so they match nothing.
orders.filter(F.col("amount").isNull()).show()
null_counts = orders.select(
[F.count(F.when(F.col(c).isNull(), 1)).alias(c) for c in orders.columns]
)
null_counts.show()The second query profiles every column in one pass. F.when without otherwise returns null for non-matching rows, and count skips nulls, so it counts only the rows where the column is null.
Why comparisons with null behave oddly
Spark uses three-valued logic. A comparison involving null returns null, not true or false. filter keeps only rows where the condition is true, so rows with a null result are dropped.
orders.filter(F.col("amount") != 120.0).show()This returns rows 2, 3, 5 and 6. Row 4, with the null amount, is missing even though a null amount is arguably "not 120". If you want to keep it, say so explicitly:
orders.filter((F.col("amount") != 120.0) | F.col("amount").isNull()).show()The same rule applies to joins. Rows whose join key is null never match, even against another null. To treat two nulls as equal, use a null-safe comparison:
other = spark.createDataFrame([(None, "unknown")], "customer STRING, tag STRING")
orders.join(other, orders.customer.eqNullSafe(other.customer), "left").show()Aggregations and nulls
Aggregate functions mostly skip nulls, but count depends on its argument.
| Expression | Null handling |
|---|---|
| `F.count("*")` | Counts every row |
| `F.count("amount")` | Counts only rows where `amount` is not null |
| `F.sum("amount")`, `F.avg("amount")` | Ignore nulls. The result is null if every value is null |
| `groupBy("customer")` | Null forms its own group |
Because avg ignores nulls, replacing nulls with zero before averaging changes the answer. Decide whether a missing amount means "unknown" or "zero" before you fill it.
Handling nulls: drop, fill or substitute
You have three options. Pick based on what the missing value means.
# Drop rows with a null in the listed columns
orders.dropna(subset=["amount"]).show()
# Fill nulls per column. The value type must match the column type.
orders.fillna({"amount": 0.0, "customer": "unknown"}).show()
# Substitute only where needed, keeping the original column intact
orders.withColumn("amount_clean", F.coalesce("amount", F.lit(0.0))).show()dropna has how="any" (the default, which drops a row if any checked column is null) and how="all". It also accepts thresh=N, which keeps rows with at least N non-null values. F.coalesce returns the first non-null argument. It is the right tool when the fallback comes from another column or when you want to keep the original value beside the cleaned one.
Finding and removing duplicates
Two kinds of duplicate occur. A fully identical row repeats every column. A key duplicate repeats the business key, such as customer and order date, while other columns differ.
First, measure the problem:
orders.groupBy("customer", "order_date").count().filter("count > 1").show()distinct() removes rows identical in every column. In our data, rows 3 and 5 differ in order_id, so distinct() removes nothing. For key duplicates, use dropDuplicates with a column list:
deduped = orders.dropDuplicates(["customer", "order_date"])
deduped.show()dropDuplicates treats null values in the key columns as equal to each other. It also keeps an unspecified row from each group. Spark does not promise that it will be the first, the lowest id or the most recent. If the choice matters, rank the rows yourself:
w = Window.partitionBy("customer", "order_date").orderBy(F.col("order_id").desc())
latest = (
orders
.withColumn("rn", F.row_number().over(w))
.filter("rn = 1")
.drop("rn")
)
latest.show()This keeps the row with the highest order_id in each group, and the result is the same on every run. Both approaches trigger a shuffle, because rows with the same key must be brought together. See the performance chapter for how to read that in a query plan.
Common errors
- Writing
col == None. UseisNull(). - Filtering with
!=orNOT INand losing null rows without noticing. - Expecting
dropDuplicates(["a"])to keep a particular row. Use a window withrow_number. - Using
count("amount")when you meant the number of rows. Usecount("*"). - Filling nulls with 0 before computing an average, which pulls the average down.
- Deduplicating before cleaning keys. Values like
"Alice"and"alice "are different strings, so normalize withF.lower(F.trim("customer"))first.
Exercise
Using the orders DataFrame above, write a query that returns each customer's order count and average amount, treating the null customer as the label "unknown", and explain why count("*") and count("amount") differ for carol.
Show answer
Use orders.withColumn("customer", F.coalesce("customer", F.lit("unknown"))).groupBy("customer").agg(F.count("*").alias("order_count"), F.avg("amount").alias("avg_amount")). For carol, count("*") is 1 because it counts the row. count("amount") is 0 because her only amount is null, and count on a column skips nulls. Her avg_amount is also null, because avg has no non-null values to average.
Exercise
Rows 3 and 5 are the same order saved twice with different ids. Why does orders.distinct() keep both, and how would you keep only row 5 deterministically?
Show answer
distinct() compares every column, and order_id differs (3 versus 5), so the rows are not identical. To keep row 5, define a window Window.partitionBy("customer", "order_date").orderBy(F.col("order_id").desc()), add F.row_number().over(w) as a column, keep rows where it equals 1, and drop the helper column.