Sub topic 7
Full, semi, anti, and cross joins
This chapter assumes you know inner and left joins, and the on, left_on, and right_on arguments from earlier chapters. The four joins here cover cases those two can't: keeping unmatched rows from both sides, filtering one table by another, and pairing every row with every row.
Which side survives
The tables below are used in all examples.
import polars as pl
customers = pl.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Cy"],
})
orders = pl.DataFrame({
"order_id": [100, 101, 102],
"customer_id": [1, 1, 4],
"amount": [30, 20, 50],
})Customers 2 and 3 have no orders. Order 102 belongs to customer 4, who is not in customers.
Full join
A full join keeps every row from both tables. Unmatched rows get null in the columns from the other side.
full = customers.join(orders, on="customer_id", how="full", coalesce=True).sort("customer_id")
print(full)The result has five rows. Ben and Cy have null order_id and amount. Order 102 has a null name.
Semi and anti joins
Semi and anti joins are filters. They return only the columns of the left table, and they never duplicate left rows.
with_orders = customers.join(orders, on="customer_id", how="semi")
without_orders = customers.join(orders, on="customer_id", how="anti")
print(with_orders) # Ana only
print(without_orders) # Ben and CyAn inner join would return Ana twice, because she has two orders. A semi join returns her once. Use semi to ask "which customers have at least one order?" and anti to ask "which customers have none?"
Cross join
A cross join pairs every left row with every right row. It takes no key, so you leave out on.
sizes = pl.DataFrame({"size": ["S", "M"]})
colors = pl.DataFrame({"color": ["red", "blue"]})
variants = sizes.join(colors, how="cross")
print(variants) # 4 rows: S-red, S-blue, M-red, M-blueThe output height is the left height times the right height. Joining two tables of 10,000 rows each gives 100 million rows, so check the sizes first.
Choosing among them
| Goal | Join |
|---|---|
| Keep all rows from both tables | `full` |
| Keep left rows that have a match, no right columns | `semi` |
| Keep left rows that have no match | `anti` |
| Build every combination | `cross` |
Common errors
- Passing
onwithhow="cross"raises an error, because cross joins have no keys. - Expecting right-hand columns from
semioranti. They return none. - Forgetting
coalesce=Trueon a full join and then filtering oncustomer_id, which is null for right-only rows. - Relying on row order. Join output order is not guaranteed, so call
sortwhen order matters.
Exercise
Using the customers and orders tables above, which join returns only the orders whose customer is missing from customers, and what is the call?
Show answer
An anti join with orders on the left: orders.join(customers, on="customer_id", how="anti"). It returns order 102 (customer 4) and only the columns of orders.