Sub topic 5
Combining tables with inner and left joins
This chapter assumes you can create a Polars DataFrame and know what a key column is. It covers the two joins you will use most: inner and left.
What a join does
A join combines two DataFrames by matching rows on key columns. The call is left.join(right, on="key", how=...). The how argument decides what happens to rows that have no match on the other side.
The examples use two small tables. Order 102 belongs to customer 4, who is not in the customers table.
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],
})Inner join
An inner join keeps only rows whose key appears in both tables. Unmatched rows from either side are dropped.
inner = orders.join(customers, on="customer_id", how="inner")
print(inner) # orders 100 and 101 only, each with name "Ana"Order 102 is gone, and customers 2 and 3 never appear because they have no orders. Use an inner join when an unmatched row is not useful to you.
Left join
A left join keeps every row of the left table. Where the right table has no match, the right-hand columns are filled with null.
left = orders.join(customers, on="customer_id", how="left")
print(left) # order 102 is kept, with name nullThe result has the left table's columns first, followed by the right table's non-key columns. Use a left join when the left table is your main data and the right table only adds detail.
Common errors
- Row count grows unexpectedly. If the right table has several rows for one key, each left row is repeated once per match. A left join never drops rows, but it can add them. Check
df.heightbefore and after. - Key types differ. Joining an
Int64column to anInt32column, or to aStringcolumn, raises an error. Cast one side first, for examplepl.col("customer_id").cast(pl.Int64). - Null keys do not match. By default, a null key never matches another null. Rows with null keys survive a left join, but they get no right-hand data.
- Reading nulls as bad data. A null in
nameafter a left join means "no match". The right table can also hold real nulls, so use an anti join (covered later) when you need to list unmatched rows.
Choosing between them
| Question | Join |
|---|---|
| Do I want only rows that exist in both tables? | inner |
| Must every row of my main table survive? | left |
Exercise
Using the orders and customers tables above, how many rows does customers.join(orders, on="customer_id", how="left") return, and which customers have null in order_id?
Show answer
It returns 4 rows. Customer 1 matches two orders, so Ana appears twice. Ben (2) and Cy (3) have no orders and appear once each with null in order_id and amount. Order 102 does not appear because its customer, 4, is not in the left table.