Sub topic 11
Joins and concatenation
This chapter assumes you know pd.merge, DataFrame.join and pd.concat, and that you have read the earlier chapters on expressions and the no-index model. It maps each operation to its Polars equivalent and covers the places where results differ.
Merge becomes join
Polars has one method, DataFrame.join, for column-based joins. It has no index to join on, so there is no separate index join like pandas df.join.
The examples below use two small frames.
import pandas as pd
import polars as pl
customers = pl.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Cy"],
"region": ["EU", "US", "EU"],
})
orders = pl.DataFrame({
"order_id": [10, 11, 12, 13],
"customer_id": [1, 1, 2, 4],
"total": [120.0, 80.0, 50.0, 200.0],
})
# pandas
pdf = orders.to_pandas().merge(
customers.to_pandas(), on="customer_id", how="left"
)
# Polars
joined = orders.join(customers, on="customer_id", how="left")
print(joined)Order 13 belongs to customer 4, who is not in customers, so its name and region are null. The to_pandas calls need pyarrow installed.
| pandas `merge` | Polars `join` |
|---|---|
| `on="k"` | `on="k"` |
| `left_on="a", right_on="b"` | `left_on="a", right_on="b"` |
| `how="inner"` (the default) | `how="inner"` (the default) |
| `how="outer"` | `how="full"` |
| `how="cross"` | `how="cross"` |
| `suffixes=("_x", "_y")` | `suffix="_right"` (one suffix, for right-side duplicates only) |
| `validate="many_to_one"` | `validate="m:1"` |
| `indicator=True` | No direct equivalent. Use `how="anti"` or `how="semi"`. |
| `how="left"` plus a filter on a missing match | `how="anti"` or `how="semi"` |
Polars also adds two filtering joins. A semi join keeps the left rows that have a match and adds no columns. An anti join keeps the left rows that have no match.
# Orders whose customer is unknown
unknown = orders.join(customers, on="customer_id", how="anti")
# Orders from customers we know, without adding customer columns
known = orders.join(customers, on="customer_id", how="semi")Differences that change results
Key columns
With left_on and right_on, pandas keeps both key columns. Polars keeps only the left key for inner and left joins.
a = pl.DataFrame({"id": [1, 2], "x": ["a", "b"]})
b = pl.DataFrame({"cust": [1, 2], "y": ["c", "d"]})
print(a.join(b, left_on="id", right_on="cust").columns)
# ['id', 'x', 'y']A full join does not merge the keys by default. Unmatched right rows show up with a null id and a populated id_right. Pass coalesce=True to get one key column, which is what a pandas outer merge on a shared on column gives you.
a = pl.DataFrame({"id": [1, 2], "x": ["a", "b"]})
b = pl.DataFrame({"id": [2, 3], "y": ["c", "d"]})
print(a.join(b, on="id", how="full", coalesce=True))Null keys
pandas merge matches missing keys to each other. Polars does not match nulls by default, so rows with a null key never pair up. Newer releases expose this as nulls_equal=True and older ones as join_nulls=True. Check which one your installed version has. If you port code that relied on null-to-null matching, the row counts change without any error.
Row order
Do not rely on the row order of a join result. pandas documents an order for each join type. Polars gives no such guarantee unless you ask for it, either with the maintain_order argument (available in recent versions) or with an explicit .sort(...) after the join. When you validate against pandas output, sort both sides first.
Duplicate column names
If both frames have a non-key column with the same name, Polars renames only the right one, adding _right (change this with suffix). The left column keeps its name. pandas renames both sides, to _x and _y. Code that refers to col_x after a merge must be updated.
Guarding against fan-out
A many-to-many key mix silently multiplies rows in both libraries. Use validate to fail early:
# Raises if customer_id is not unique in the right frame
orders.join(customers, on="customer_id", how="left", validate="m:1")Allowed values are "m:m" (the default, no check), "1:m", "m:1" and "1:1".
Joining on conditions and on time
pd.merge_asof maps to join_asof. Both frames must be sorted by the key, and the default strategy is "backward", as in pandas.
trades = pl.DataFrame({
"ts": [3, 7, 12],
"sym": ["A", "A", "A"],
"qty": [10, 20, 30],
})
quotes = pl.DataFrame({
"ts": [1, 5, 10],
"sym": ["A", "A", "A"],
"px": [100.0, 101.0, 102.0],
})
print(trades.join_asof(quotes, on="ts", by="sym", strategy="backward"))Each trade receives the most recent quote at or before its timestamp. Use strategy="forward" or "nearest" for the other directions. For inequality conditions such as range joins, recent Polars releases offer join_where. It is newer and still marked unstable in some versions, so check the documentation for your installed version first.
Concat becomes pl.concat
pd.concat has one axis argument. Polars uses a how argument and is stricter about schemas.
| pandas | Polars |
|---|---|
| `pd.concat([a, b])` | `pl.concat([a, b])` (`how="vertical"`) |
| `pd.concat([a, b], ignore_index=True)` | Same call. There is no index to reset. |
| Stack frames with different columns | `how="diagonal"` fills the gaps with null |
| `pd.concat([a, b], axis=1)` | `how="horizontal"` |
q1 = pl.DataFrame({"id": [1, 2], "amount": [10, 20]})
q2 = pl.DataFrame({"id": [3], "amount": [30], "note": ["late"]})
# Vertical concat would raise because q2 has an extra column
combined = pl.concat([q1, q2], how="diagonal")
print(combined)Plain vertical concatenation raises an error when column names or dtypes differ. pandas would quietly upcast or add columns. If one frame has Int32 and the other Int64, use how="vertical_relaxed". It casts to a common supertype. diagonal_relaxed combines both behaviours. The strictness is deliberate, because it exposes schema drift that pandas hides. Cast explicitly when you know the difference is harmless.
Horizontal concat has no alignment. Frames are placed side by side by position, and their heights must match (shorter frames may be padded with nulls in some versions). If you used axis=1 to align on the index, you need a join instead.
Migration checklist
- Replace
how="outer"withhow="full", and addcoalesce=Trueif downstream code expects one key column. - Search for
_xand_ycolumn references and replace them with the new suffix behaviour. - Decide whether null keys should match, and set the null-matching argument explicitly.
- Add
validate=to joins that you believe arem:1. - Sort before comparing results.
- Replace
axis=1concats with joins unless row positions truly correspond.
Exercise
In pandas you ran left.merge(right, on="id", how="outer") and then used result["id"] with no nulls. After a direct port to left.join(right, on="id", how="full") the id column contains nulls. Why, and how do you fix it?
Show answer
A Polars full join does not coalesce the key columns. Rows that exist only in right get a null in the left id column, and their key appears in id_right. Pass coalesce=True to join so that one id column is filled from whichever side has the row.
Exercise
You concatenate a frame whose amount is Int32 with one whose amount is Int64 using pl.concat([a, b]), and Polars raises an error. Name two ways to resolve it.
Show answer
Cast one frame's column to match the other with .cast(pl.Int64) before concatenating, or call pl.concat([a, b], how="vertical_relaxed") so Polars casts to the common supertype.