Sub topic 11
Joining DataFrames
This chapter assumes you can build a DataFrame, write expressions with pl.col, and use select, with_columns and filter. Joins combine two DataFrames by matching rows on key columns. The result keeps Polars' column-first style: you name the keys, pick a join type, and get a new DataFrame.
A basic left join
The employee DataFrame has a dept column. A second DataFrame describes each department. A left join keeps every row of the left frame and adds matching columns from the right.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
depts = pl.DataFrame({"dept": ["eng", "ops"], "floor": [3, 1]})
joined = df.join(depts, on="dept", how="left")
print(joined)The output has the original columns plus floor. Each row keeps its position, so Ana and Ben both get floor 3.
Choosing a join type
The how argument controls which rows survive.
| `how` | Rows in the result |
|---|---|
| `"inner"` | Only keys present in both frames (the default). |
| `"left"` | All left rows. Unmatched right columns are null. |
| `"right"` | All right rows. Unmatched left columns are null. |
| `"full"` | All rows from both frames. |
| `"semi"` | Left rows that have a match. No right columns are added. |
| `"anti"` | Left rows that have no match. |
| `"cross"` | Every left row paired with every right row. No keys are used. |
Semi and anti joins act as filters. They are a clean way to ask "which employees belong to a known department?" without carrying extra columns.
known = df.join(depts, on="dept", how="semi")
missing = df.join(depts, on="dept", how="anti")Keys with different names
When the key columns have different names, use left_on and right_on.
depts2 = pl.DataFrame({"dept_code": ["eng", "ops"], "floor": [3, 1]})
joined2 = df.join(depts2, left_on="dept", right_on="dept_code", how="left")
print(joined2)You can pass lists to both arguments to join on several columns. The two lists must have the same length.
Common errors
- Mismatched key dtypes. Joining an
Int64column to aStringcolumn raises an error. Cast one side first, for example withpl.col("id").cast(pl.Int64). - Nulls never match. By default a null key does not match another null key. Pass
nulls_equal=Trueif you want them to match. - Duplicate keys multiply rows. If the right frame has two rows for
eng, eachengrow on the left appears twice. Check uniqueness withdepts.select(pl.col("dept").is_duplicated().any()), or use thevalidateargument, such asvalidate="m:1", to make Polars raise an error when the assumption fails. - Name collisions. If both frames have a non-key column called
floor, the right one is renamedfloor_right. Change this with thesuffixargument. - Row order. Do not rely on the order of join output unless you set
maintain_order. Sort explicitly when order matters.
safe = df.join(depts, on="dept", how="left", validate="m:1")The code "m:1" means many left rows may match one right row. Polars checks this and raises an error if depts has repeated keys.
How a join flows
The diagram shows the left-join steps for one row.
Exercise
You join df to a depts frame that accidentally lists "eng" twice, using how="left". How many rows does the result have, and how can you make Polars catch this?
Show answer
Ana and Ben each match two rows, so the result has 6 rows instead of 4. Pass validate="m:1" to join, and Polars raises an error because the right frame has duplicate keys.