Sub topic 11
Joining DataFrames
This chapter assumes you know the contexts (select, with_columns, filter) and how group_by works. It also assumes you can read a DataFrame schema. Joins combine two DataFrames by matching values in key columns. In Polars they are DataFrame methods, not expressions, so they sit outside the contexts you have used so far.
The basic join
DataFrame.join takes another DataFrame, the key column or columns (on), and a join type (how). The default is "inner".
import polars as pl
employees = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "hr"],
"salary": [120, 100, 80, 90],
}
)
depts = pl.DataFrame({"dept": ["eng", "ops", "fin"], "floor": [3, 1, 2]})
joined = employees.join(depts, on="dept", how="left")
print(joined.sort("name"))Every employee row is kept. Dee's department hr has no match in depts, so her floor is null. The fin row in depts has no employees, so a left join drops it.
Choosing a join type
The how argument decides which unmatched rows survive.
| `how` | Rows returned | Columns returned |
|---|---|---|
| `"inner"` | Only keys present on both sides | Both sides |
| `"left"` | All left rows, matched right values or null | Both sides |
| `"right"` | All right rows, matched left values or null | Both sides |
| `"full"` | All rows from both sides | Both sides |
| `"semi"` | Left rows that have a match | Left only |
| `"anti"` | Left rows that have no match | Left only |
| `"cross"` | Every left row paired with every right row | Both sides |
for how in ["inner", "left", "right", "full", "semi", "anti"]:
print(how)
print(employees.join(depts, on="dept", how=how).sort("name"))semi and anti are filters that use another table as the condition. They never add columns and never multiply rows, so they are the safest way to ask "which employees belong to a known department?" or "which do not?".
Full joins and key columns
With how="full", Polars keeps the right key as a separate column named dept_right. For rows that exist only on the right, dept is null and dept_right holds the value. Pass coalesce=True to merge the two key columns into one:
print(employees.join(depts, on="dept", how="full", coalesce=True).sort("dept"))For inner and left joins the right key column is dropped by default, because it duplicates the left one.
Keys with different names
Use left_on and right_on when the key columns are named differently. Use suffix when non-key columns share a name.
orders = pl.DataFrame(
{"order_id": [1, 2, 3], "cust_id": [10, 11, 10], "note": ["a", "b", "c"]}
)
customers = pl.DataFrame({"id": [10, 11, 12], "note": ["vip", "new", "lapsed"]})
print(orders.join(customers, left_on="cust_id", right_on="id", suffix="_cust"))Both frames have a note column. The right one is renamed note_cust. Without suffix, the default is _right. The id column is dropped, and cust_id stays.
You can join on several keys with a list, such as on=["dept", "year"]. A row matches only if all keys are equal. You can also pass expressions as keys, for example left_on=pl.col("dept").str.to_lowercase(). Then you transform the key during the join, with no extra step before it.
Duplicate keys multiply rows
A join pairs every matching left row with every matching right row. If a key appears twice on the right, each left row with that key appears twice in the result.
dup = pl.DataFrame({"dept": ["eng", "eng"], "floor": [3, 4]})
print(employees.join(dup, on="dept", how="left").height) # 6, not 4This is the most common join bug. Row counts silently grow, and later aggregates such as sums are inflated. The validate argument turns the silent bug into an error:
try:
employees.join(dup, on="dept", how="left", validate="m:1")
except pl.exceptions.PolarsError as err:
print("join check failed:", err)The accepted values are "m:m" (the default, no check), "1:m", "m:1" and "1:1". Read them as left:right. In "m:1", many left rows may share a key, but each key must be unique on the right. That is the usual shape of a lookup table such as depts.
Nulls and row order
By default, null keys never match each other, even though both are null. A left row with a null key therefore gets nulls in the right columns. Polars has an option to treat nulls as equal. It is called join_nulls in older releases and nulls_equal in newer ones, so check your installed version's documentation. Only enable it if nulls in your keys really mean "the same unknown group".
Key dtypes must be compatible. Joining an Int64 key to a String key raises an error instead of coercing. Cast one side first:
fixed = orders.join(
customers.with_columns(pl.col("id").cast(pl.Int64)),
left_on="cust_id",
right_on="id",
)Joins in the lazy API
LazyFrame.join works the same way, but both sides must be lazy. The optimizer can then push filters and column selections below the join, so less data is joined.
result = (
employees.lazy()
.join(depts.lazy(), on="dept", how="left")
.filter(pl.col("salary") >= 90)
.select("name", "floor")
.collect()
)
print(result.sort("name"))A filter on a left-side column, written after the join, can be applied before it. explain() shows where the filter ended up. Mixing a LazyFrame with a DataFrame raises a type error, so call .lazy() on the eager frame first.
Related join methods
df.join_asof(other, on="time")matches each left row to the nearest earlier (or later) right row. Both frames must be sorted by the key. It is used for time series such as trades and quotes.df.join_where(other, condition)joins on inequality conditions such aspl.col("a") < pl.col("b"). It exists in recent releases, and some versions mark it experimental.df.join(other, how="cross")takes no key. The result hasleft.height * right.heightrows, so check the sizes first.pl.concat(..., how="horizontal")glues frames side by side by position, with no key matching. Use it only when row alignment is already guaranteed.
Common mistakes
- Using an inner join when you meant a left join. Unmatched rows vanish without any warning.
- Forgetting that the right table has duplicate keys, which inflates counts and sums.
- Expecting pandas-style
suffixeson every column. Polars appliessuffixonly to right-side columns whose names collide. - Comparing results without sorting them.
- Joining on columns with different dtypes, or with trailing spaces or mixed case in strings. Normalize keys first with
str.strip_chars()orstr.to_lowercase().
Exercise
You run employees.join(depts, on="dept", how="left") and the result has more rows than employees. What is the likely cause, and which argument would have caught it?
Show answer
The depts table contains the same dept value more than once, so each matching employee row is repeated for every duplicate. Passing validate="m:1" makes Polars raise an error when the right-side keys are not unique.
Exercise
Write a Polars expression chain that returns only the employees whose department has no row in depts, with no columns from depts added.
Show answer
employees.join(depts, on="dept", how="anti"). An anti join keeps left rows that have no match and returns only left columns. For the example data, the result is Dee's row.
Exercise
Why can employees.lazy().join(depts, on="dept") fail, and how do you fix it?
Show answer
A LazyFrame can only be joined with another LazyFrame. Passing the eager depts DataFrame raises a type error. Fix it with employees.lazy().join(depts.lazy(), on="dept").