Sub topic 13
Joining DataFrames
This chapter assumes you can create a DataFrame, select and filter columns, and run grouped aggregations. It also assumes you know that transformations are lazy and that an action such as display runs them.
What a join does
A join combines two DataFrames by matching rows on a key. Each row of the left DataFrame is compared with rows of the right DataFrame. Rows that satisfy the join condition are combined into one row.
The example uses the orders DataFrame from earlier chapters and a small customers DataFrame.
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),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
customers = spark.createDataFrame(
[("alice", "US"), ("bob", "DE")],
"customer STRING, country STRING",
)
enriched = orders.join(customers, on="customer", how="left")
display(enriched)Passing on="customer" joins on a column that has the same name in both DataFrames. The result contains one customer column. Carol has no match in customers, so her row stays and country is null.
Choosing a join type
The how argument sets which rows survive.
| `how` value | Result |
|---|---|
| `inner` (default) | Only rows with a match on both sides |
| `left` | All left rows, with nulls where the right side has no match |
| `right` | All right rows, with nulls where the left side has no match |
| `full` | All rows from both sides |
| `left_semi` | Left rows that have a match, with only the left columns |
| `left_anti` | Left rows that have no match, with only the left columns |
left_anti is a convenient way to find missing data. This query returns Carol's orders:
orders.join(customers, on="customer", how="left_anti").show()Joining on different column names
When the key columns have different names, use a condition expression. Both columns are kept in the result, so drop one of them afterward.
customers2 = customers.withColumnRenamed("customer", "customer_name")
joined = orders.join(
customers2,
on=orders["customer"] == customers2["customer_name"],
how="inner",
).drop("customer_name")
display(joined)Common errors
- Ambiguous column. If you join with a condition and both sides have a column called
customer, selecting"customer"fails with an ambiguity error. Reference columns through their DataFrames, such asorders["customer"]. You can also rename or drop one side before the join. - Unexpected row growth. If the right side has several rows per key, each left row is repeated once per match. Check key uniqueness with
groupBy("customer").count()before you join. - Null keys never match. A null in a join key does not equal another null, so those rows are dropped by an inner join.
- Wrong type on the key. Joining a string column to an integer column may cast silently or return no matches. Check both schemas with
printSchema().
Exercise
You run orders.join(customers, "customer") with no how argument. Which rows does the result contain, and is Carol's order among them?
Show answer
The default is an inner join, so only orders with a matching customer remain. Carol's order is not in the result because customers has no row for her. Use how="left" to keep it.
Exercise
Write a join that returns every customer in customers along with their orders, including customers who have no orders yet.
Show answer
Make customers the left side of a left join: customers.join(orders, on="customer", how="left"). You can also keep the original order and use how="right", but putting the DataFrame you want to keep on the left is easier to read.