Sub topic 5
Combining tables with inner and left joins
This chapter covers the two joins you will use most often in Polars: the inner join and the left join. It assumes you can create a DataFrame, select columns with pl.col, and read a group_by result. It also assumes you know what a key column is, meaning a column whose values identify the same entity in two tables.
What a join does
A join combines two DataFrames by matching rows on key values. For each row in the left table, Polars looks for rows in the right table with an equal key. When it finds matches, it produces one output row per match, containing the columns from both sides.
A join differs from group_by in the shape of its result. group_by produces one row per group. A join produces rows based on matches, so the output can have fewer rows, the same number, or more rows than either input.
The two joins in this chapter differ only in what happens to rows that find no match:
- Inner join: keeps only rows whose key exists in both tables.
- Left join: keeps every row of the left table. Where the right table has no match, the right-side columns are filled with null.
A first join
The example uses three customers and three orders. Order 102 belongs to customer 4, who does not exist 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],
})
left = orders.join(customers, on="customer_id", how="left")
inner = orders.join(customers, on="customer_id", how="inner")
print(left) # 3 rows; order 102 has name null
print(inner) # 2 rows; orders 100 and 101 onlyThe left join returns three rows, one for each order. Order 102 stays, and its name is null because no customer 4 exists. The inner join returns two rows. Order 102 is dropped because its key has no partner.
The output columns are order_id, customer_id, amount, and name. The key column customer_id appears once, not twice, because on="customer_id" tells Polars the two columns are the same thing. Columns from the left table come first, followed by the non-key columns of the right table.
The calling table is the left table
how="left" means the table you call .join on. The two lines below answer different questions:
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],
})
orders_with_names = orders.join(customers, on="customer_id", how="left")
customers_with_orders = customers.join(orders, on="customer_id", how="left")
print(orders_with_names.height) # 3: every order kept
print(customers_with_orders.height) # 4: Ana twice, Ben and Cy once eachThe second join keeps every customer. Ana matches two orders, so she appears twice. Ben and Cy match nothing, so each appears once with null order_id and amount. Choose the left table by asking which rows you must not lose. Here the question is whether you need every order or every customer.
For an inner join, the choice of left table does not change which rows are kept. Only the column order and possibly the row order change.
Reading the nulls from a left join
Nulls in right-side columns after a left join mean "no match found." You can use this to count or filter unmatched rows:
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],
})
left = orders.join(customers, on="customer_id", how="left")
missing = left.filter(pl.col("name").is_null())
print(missing) # order 102 onlyThis check has a weakness. If a matched customer genuinely has a null name, the filter cannot tell it apart from a failed match. Filtering on a right-side column that is never null for real matches, such as the key or an ID, is more reliable. The dedicated anti join, covered in a later chapter, answers this question directly.
When a join multiplies rows
A join produces one output row for every pair of matching rows. If the key is unique in the right table, each left row matches at most once and a left join keeps the row count unchanged. If the key repeats in the right table, left rows are duplicated.
import polars as pl
orders = pl.DataFrame({
"order_id": [100, 101, 102],
"customer_id": [1, 1, 4],
"amount": [30, 20, 50],
})
dup_customers = pl.DataFrame({
"customer_id": [1, 1, 2],
"name": ["Ana", "Ana B.", "Ben"],
})
out = orders.join(dup_customers, on="customer_id", how="left")
print(out.height) # 5, not 3
print(out.select(pl.col("amount").sum())) # 130, not 100Orders 100 and 101 each match two customer rows, so each appears twice. Order 102 has no match and appears once. The row count rises from 3 to 5, and the sum of amount rises from 100 to 130.
This is the most common join bug. The join succeeds and gives no error, but later totals are inflated. Two habits help:
- Compare row counts before and after a left join when you expect them to stay equal.
- Check that the key is unique on the side you expect to be "one." A later chapter shows Polars' built-in
validateoption for this.
Row order
Do not rely on the row order of a join result. Recent Polars versions have a maintain_order parameter on join, and its default makes no ordering guarantee. Earlier versions behaved differently, particularly for inner joins. If order matters, either request it or sort the result explicitly:
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],
})
out = orders.join(customers, on="customer_id", how="inner").sort("order_id")
print(out)Sorting after the join gives the same output on any version, which also makes tests and printed examples reproducible.
Key dtypes must agree
Both key columns need compatible data types. Joining an Int64 column against a String column raises an error rather than coercing silently. Cast one side first:
import polars as pl
a = pl.DataFrame({"id": [1, 2], "x": ["p", "q"]})
b = pl.DataFrame({"id": ["1", "2"], "y": [10, 20]})
out = a.join(b.with_columns(pl.col("id").cast(pl.Int64)), on="id", how="inner")
print(out) # 2 rowsInteger widths such as Int32 and Int64 are the usual source of this mismatch when data comes from different files. A cast to a common type fixes it.
Choosing between inner and left
| Question you are asking | Join | Left table |
|---|---|---|
| Which orders have a known customer? | inner | either |
| Show every order, with customer info when available | left | orders |
| Show every customer, with their orders when available | left | customers |
| Do any orders lack a customer? | left, then check nulls | orders |
Use an inner join when unmatched rows are noise you want removed. Use a left join when dropping rows would hide information. A left join keeps your main table intact, which makes it the safer default when you are enriching one table with attributes from another.
Exercise
A table orders has 1,000 rows. You run orders.join(products, on="product_id", how="left") and the result has 1,040 rows. What is the most likely cause, and how would you confirm it?
Show answer
The product_id key is not unique in products, so some orders matched more than one product row and were duplicated. Confirm it by counting repeated keys, for example products.filter(pl.col("product_id").is_duplicated()), or by running products.select(pl.col("product_id").n_unique()) and comparing it with products.height. Fix it by deduplicating products or by correcting the source data.
Exercise
Given orders and customers from this chapter, which join and which left table would you use to list every customer together with their total order amount, showing customers with no orders too?
Show answer
Use a left join with customers as the left table, for example customers.join(orders, on="customer_id", how="left"). Customers with no orders are kept with null order columns. Then aggregate per customer, filling nulls with 0 if you want a zero total.