Sub topic 6
Join keys and overlapping column names
This chapter covers how to tell Polars which columns to match on, and what happens to the columns that come out of a join. It assumes you know inner and left joins from the previous chapter, can build a DataFrame, and can select columns with pl.col. Examples use a recent Polars 1.x release.
Naming the keys
A join key is a column, or a list of columns, whose values decide which rows match. DataFrame.join has three ways to name it.
| Situation | Arguments | Example |
|---|---|---|
| Same name on both sides | `on` | `on="customer_id"` |
| Different names | `left_on` and `right_on` | `left_on="customer_id", right_on="id"` |
| More than one column | a list for any of the above | `on=["region", "product"]` |
on is shorthand for setting left_on and right_on to the same value. You cannot combine on with left_on or right_on. If you pass left_on, you must also pass right_on.
Different key names
Here the orders table calls the key customer_id, and the customers table calls it id.
import polars as pl
customers = pl.DataFrame({
"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, left_on="customer_id", right_on="id", how="left")
print(out.columns) # ['order_id', 'customer_id', 'amount', 'name']
print(out) # order 102 has name nullThe result has no id column. For inner and left joins, the matched key values are identical on both sides, so Polars keeps the left key and drops the right one. This is called coalescing the key columns.
Composite keys
A composite key is a key made of several columns. A row matches only if every key column matches.
sales = pl.DataFrame({
"region": ["east", "east", "west"],
"product": ["a", "b", "a"],
"units": [10, 20, 5],
})
prices = pl.DataFrame({
"region": ["east", "east", "west"],
"product": ["a", "b", "b"],
"price": [2.0, 3.0, 4.0],
})
out = sales.join(prices, on=["region", "product"], how="left")
print(out) # east/a -> 2.0, east/b -> 3.0, west/a -> nullThe pair ("west", "a") exists in sales but not in prices, so its price is null. Matching on region alone would pair each sales row with every price in that region. That would add rows and give wrong answers. If you use left_on and right_on with lists, the lists must have the same length. Columns are paired by position.
Key columns in the output
Which key columns survive depends on the join type and the coalesce parameter.
coalesce=Noneis the default. Polars coalesces forinnerandleftjoins and does not coalesce forfulljoins.coalesce=Trueforces a single key column.coalesce=Falsekeeps both key columns.
Full joins need this behavior. A row that exists only on the right has a null in the left key, so the left key alone loses information. By default, the right key appears as an extra column named with the suffix _right.
a = pl.DataFrame({"k": [1, 2], "x": ["a", "b"]})
b = pl.DataFrame({"k": [2, 3], "y": ["c", "d"]})
full = a.join(b, on="k", how="full").sort("k")
print(full.columns) # ['k', 'x', 'k_right', 'y']
print(full) # k is null on the row that exists only in b
merged = a.join(b, on="k", how="full", coalesce=True).sort("k")
print(merged.columns) # ['k', 'x', 'y']
print(merged) # k is 1, 2, 3; x is a, b, null; y is null, c, dWithout coalesce=True, sorting on k puts the null-key row last or first depending on settings. In the first result, check k_right to see the key for that row.
You can keep both key columns in a left join too. This is useful when you want to see which right-side key matched.
out = orders.join(
customers,
left_on="customer_id",
right_on="id",
how="left",
coalesce=False,
)
print(out.columns) # ['order_id', 'customer_id', 'amount', 'id', 'name']
print(out) # id is null for order 102Here id is null exactly where no customer matched. That makes coalesce=False a quick way to find unmatched rows, although an anti join states that intent more directly.
Overlapping column names
A DataFrame cannot hold two columns with the same name. Suppose both tables have a non-key column called status. Polars keeps the left column as it is and renames the right one by appending a suffix. The default suffix is _right.
orders = pl.DataFrame({
"order_id": [100, 101],
"customer_id": [1, 2],
"status": ["shipped", "open"],
})
customers = pl.DataFrame({
"customer_id": [1, 2],
"status": ["gold", "basic"],
})
default = orders.join(customers, on="customer_id")
print(default.columns) # ['order_id', 'customer_id', 'status', 'status_right']
named = orders.join(customers, on="customer_id", suffix="_customer")
print(named.columns) # ['order_id', 'customer_id', 'status', 'status_customer']Three points about suffixes:
- The suffix applies only to right-side columns that collide with a left-side name. Columns without a collision keep their names.
- The left column is never renamed. After a join,
statusis the order status. The name does not tell you that anotherstatusexists, so a downstream reader may not notice the ambiguity. - A suffix such as
_rightdescribes position, not meaning. Choose one that names the source table, for example_customer.
If you want to avoid collisions entirely, rename or drop columns before joining.
out = orders.join(
customers.rename({"status": "customer_tier"}),
on="customer_id",
)
print(out.columns) # ['order_id', 'customer_id', 'status', 'customer_tier']Renaming first produces names that explain themselves, so it is usually better than relying on a suffix in code that other people will read.
Common errors
Key types do not match
Join keys must have compatible data types. Joining an integer column to a string column fails instead of converting silently. In recent versions the error is a SchemaError about join key data types. Cast one side first.
left = pl.DataFrame({"id": [1, 2], "v": ["p", "q"]})
right = pl.DataFrame({"id": ["1", "2"], "w": ["x", "y"]})
# left.join(right, on="id") # raises: key dtypes do not match
fixed = left.join(
right.with_columns(pl.col("id").cast(pl.Int64)),
on="id",
)
print(fixed) # id 1 -> p, x; id 2 -> q, yCast the side that is easier to convert. If a string might hold values that are not numbers, use cast(pl.Int64, strict=False) so bad values become null, and then check how many nulls you created.
Keys that look equal but are not
Values such as "Ana" and "ana " do not match. Normalize text keys before joining, for example with str.strip_chars() and str.to_lowercase(), and do this on both tables in the same way.
Wrong column name
Naming a column that does not exist raises a ColumnNotFoundError. When you use left_on and right_on, a common cause is swapping the two names. The first name must exist in the left table, which is the one you call .join on.
Row count grows
If the right table has several rows for one key value, each left row matches all of them. The output then has more rows than the left table, even in a left join. Check that the right side is unique on the key before you join. The next chapters cover join validation for that.
Summary of the arguments
- Use
onwhen the key has the same name in both tables, andleft_onwithright_onwhen it does not. - Pass lists to join on several columns, and make the lists the same length.
innerandleftjoins keep one key column.fulljoins keep both unless you passcoalesce=True.- Use
coalesce=Falseto keep the right key column in any join. - Colliding non-key columns from the right table get the
suffix, which defaults to_right. - Cast mismatched key types, and normalize text keys, before joining.
Exercise
You run orders.join(customers, left_on="customer_id", right_on="id", how="left"). The result has no id column. Why, and how would you keep it?
Show answer
For left (and inner) joins, Polars coalesces the key columns by default. It keeps the left key, customer_id, and drops the right key, id, because matched rows have the same value in both. Pass coalesce=False to keep id. It will then be null for orders with no matching customer.
Exercise
Two tables share the columns customer_id and created_at. You join on customer_id with how="inner" and default arguments. What are the output column names for the two created_at columns, and what two ways can you make them clearer?
Show answer
The left table's column stays created_at and the right table's becomes created_at_right. You can pass a descriptive suffix, such as suffix="_customer", to get created_at_customer. You can also rename the right table's column before joining, for example customers.rename({"created_at": "customer_created_at"}).
Exercise
A sales table has columns region and product. A price table has the same columns plus price, and is unique on the pair. Why does sales.join(prices, on="region") return more rows than sales, and what fixes it?
Show answer
Joining on region alone matches each sales row to every price row in that region, so rows multiply. Join on both columns with on=["region", "product"]. The pair identifies a single price row, so each sales row matches at most one.