Sub topic 2
Join Keys and Overlapping Column Names
Assume you know basic Python, Polars DataFrames, columns, and keys. A join combines rows from two DataFrames by matching key values.
Join keys and column names
Use on when both DataFrames use the same key name. Use left_on and right_on when the names differ. For several keys, pass a list.
If both tables contain a non-key column with the same name, Polars keeps the left column and adds a suffix to the right column.
import polars as pl
orders = pl.DataFrame({
"order_id": [1, 2],
"customer_id": [10, 11],
"status": ["new", "paid"],
})
customers = pl.DataFrame({
"id": [10, 11],
"status": ["active", "inactive"],
})
out = orders.join(
customers,
left_on="customer_id",
right_on="id",
how="left",
suffix="_customer",
)
print(out)The result keeps every order. The two status columns are status and status_customer.
Full, semi, anti, and cross joins
A full join keeps unmatched rows from both tables. A semi join keeps left rows that have a match but adds no right-side columns. An anti join keeps left rows without a match. A cross join creates every possible left-right pair.
| Join | Result |
|---|---|
| `full` | All rows from both sides |
| `semi` | Matching left rows only |
| `anti` | Unmatched left rows only |
| `cross` | Every possible pair |
Validating joins and handling null keys
A join can unexpectedly multiply rows when a key is duplicated. Use validate to state the expected relationship, such as "1:1" or "m:1". Polars normally does not match null keys. Use nulls_equal=True only when null means the same identifiable value in both tables.
Per-group values with `over`
Use group_by when you want one output row per group. Use over when you want a group calculation repeated on every original row.
df = pl.DataFrame({
"region": ["east", "east", "west"],
"sales": [10, 20, 5],
})
out = df.with_columns(
pl.col("sales").sum().over("region").alias("region_total"),
(pl.col("sales") / pl.col("sales").sum().over("region")).alias("share"),
)
print(out)Exercise
Which operation keeps every original row while adding a regional total?
Show answer
Use with_columns with pl.col("sales").sum().over("region").