Preserve grain when combining DataFrames
Interpret join cardinality, null behavior and schema alignment before inspecting or writing results.
Preserve grain when combining DataFrames
Work through the decision
Two fare events join to two catalog rows that share the same station code but belong to different transit lines. Each fare appears twice and the total doubles. Would a final distinct repair the result?
Check your reasoning
Identify the dimension’s real key. If the code is only unique within a line, join on both line and station. Check uniqueness at that grain and deliberately choose how to handle unmatched events. A left join keeps those events with null dimension fields. A final distinct can hide errors or collapse legitimate repeated events. Test with a repeated station code and an unknown station.
Compare the choices
- Composite-key join
- Join on every field defining the relationship when a single field is not unique. Check row cardinality on both sides before aggregating.
- Left outer join
- Preserve every left row and use nulls for missing right-side attributes. Audit unmatched keys and compare row counts after the join.
- Union by name
- Align compatible columns by their names when combining records vertically. Understand missing-column behavior and explicit type conversions.
- Schema inspection
- Use printSchema or inspect schema fields to verify nested types, names and nullability before transformation or output. Inspect samples independently.
- Bounded result inspection
- Use a limited, explicitly ordered sample for review when order matters. Full collect transfers all selected rows to driver memory.
Test the decision
Specify a schema for input and test output nullability after an outer join. DataFrame union and unionAll append by position and preserve duplicates. Use unionByName for name-based alignment. Inspect printSchema and a small bounded sample before writing. Avoid collecting an entire distributed result merely to inspect its shape.
Practice the guide skills
- Predict row counts for a composite-key join, a cross join and a union of overlapping inputs. Watch 1:29:04 · Continue at 1:30:42 · Continue at 1:31:03
- Read string station identifiers with an explicit schema and verify output types before choosing append or overwrite. Watch 1:15:25 · Continue at 1:20:06
- Sort a small sample with a deterministic tie breaker, inspect its schema and compare taking a bounded list with iterating partitions. Watch 1:17:30 · Continue at 1:18:45 · Continue at 1:19:19
Official objectives for this lesson
Lab · Reconcile a station lookup in PySpark
Use a Python 3 virtual environment with JDK 17 or 21 available. Install PySpark with python -m pip install pyspark==4.0.1. Save the code as lab.py and run python lab.py. Predict the row count and total cents after each left join. Station A appears on two lines and one ticket uses an unknown station.
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.master("local[2]").appName("StationFares").getOrCreate()
try:
tickets = spark.createDataFrame(
[(1, "A", "red", 300), (2, "A", "blue", 450), (3, "X", "red", 200)],
"ticket int, station string, line string, cents int",
)
stations = spark.createDataFrame(
[("A", "red", "Arcade"), ("A", "blue", "Avenue")],
"station string, line string, name string",
)
for keys in [["station"], ["station", "line"]]:
joined = tickets.join(F.broadcast(stations), keys, "left")
totals = joined.agg(F.count("*").alias("n"), F.sum("cents").alias("fare")).first()
print("+".join(keys), totals.n, totals.fare)
names = joined.select("ticket", F.coalesce("name", F.lit("unknown")).alias("stop"))
for row in names.orderBy("ticket").collect():
print(row.ticket, row.stop)
finally:
spark.stop()
Check the result
station 5 1700 station+line 3 950 1 Arcade 2 Avenue 3 unknown
A station-only join matches each A ticket twice and retains the unmatched ticket once. The composite key preserves one row per ticket and reconciles to 950 cents. Broadcast affects data movement. It does not enforce uniqueness. Replace the second left join with an inner join and predict which 200 cents disappear.
Related lesson · SQL commands and logic
Preserve grain when combining DataFrames quiz
Answer 3 questions. Check each answer for an explanation.