Sub topic 11
Joins and concatenation
This chapter assumes you know pd.merge and pd.concat, and that you have read the earlier chapters on expressions and the no-index model. The examples use a recent Polars 1.x release.
From merge to join
DataFrame.merge becomes DataFrame.join. The on and how arguments work the same way. The left, inner and cross joins behave as they do in pandas.
import pandas as pd
import polars as pl
orders = pl.DataFrame({
"order_id": [1, 2, 3],
"customer_id": [10, 20, 30],
"total": [120.0, 80.0, 45.5],
})
customers = pl.DataFrame({
"customer_id": [10, 20, 40],
"name": ["Ana", "Ben", "Cy"],
})
# pandas
pd_result = orders.to_pandas().merge(
customers.to_pandas(), on="customer_id", how="left"
)
# Polars
result = orders.join(customers, on="customer_id", how="left")
print(result)Order 3 has no matching customer, so its name is null. The result has no index to reset.
Argument mapping
| pandas | Polars |
|---|---|
| `left_on`, `right_on` | `left_on`, `right_on` |
| `how="outer"` | `how="full"` |
| `suffixes=("_x", "_y")` | `suffix="_right"` (applies to the right frame only) |
| `validate="m:1"` | `validate="m:1"` |
| `indicator=True`, then filter | `how="semi"` or `how="anti"` |
| `left_index=True` | Not available. Move the index into a column first. |
A semi join keeps the left rows that have a match. An anti join keeps the left rows that have none. Both return only left-hand columns.
no_customer = orders.join(customers, on="customer_id", how="anti")Differences that change results
- Key columns in full joins. A full join keeps both key columns, so you get
customer_idandcustomer_id_right. Passcoalesce=Trueto merge them into one column. - Null keys. Polars does not match null keys to each other by default. pandas matches
NaNkeys toNaNkeys. - Row order. Do not rely on the output order. Pass
maintain_order="left"if your pandas code depended on left-frame order. - Key dtypes. Key dtypes must match. Joining an
Int64column to anInt32column raises an error. Cast one side first withpl.col("customer_id").cast(pl.Int64).
From concat to pl.concat
pl.concat takes a list of frames. The how argument replaces pandas' axis and join options.
jan = pl.DataFrame({"order_id": [1, 2], "total": [10.0, 20.0]})
feb = pl.DataFrame({"order_id": [3], "total": [30.0]})
extra = pl.DataFrame({"order_id": [4], "total": [40.0], "note": ["rush"]})
stacked = pl.concat([jan, feb]) # same schema required
ragged = pl.concat([jan, extra], how="diagonal") # missing columns become null
side = pl.concat([jan, feb.head(2)], how="horizontal")verticalis the default. Column names and dtypes must match exactly. Usehow="vertical_relaxed"to let Polars cast to a common dtype.diagonalmatches pandas' behavior when columns differ. It fills the gaps with null.horizontalaligns by position, not by index labels. This is the biggest change frompd.concat(axis=1). Use a join when you need alignment by key.
There is no ignore_index argument because there is no index.
Exercise
A pandas script runs a.merge(b, on="id", how="outer") and then filters rows where id is null. After porting it with how="full", the id column has nulls for rows that exist only in b. What happened, and how do you fix it?
Show answer
A Polars full join does not coalesce the key columns by default. Rows found only in b have a null id and carry their key in id_right. Pass coalesce=True to join so the two key columns merge into one id column.