Sub topic 15
Choosing between group_by, join, and over
This chapter assumes you can build a DataFrame, select columns with pl.col, and have seen group_by, join, and over on their own. Here you learn to pick one by looking at the shape of the result you need.
Start from the output shape
The three tools differ in how many rows they return and where the values come from.
| Tool | Rows returned | Values come from |
|---|---|---|
| `group_by` with `agg` | One per group | The same table |
| `join` | Depends on the join type and key matches | Another table |
| `over` | Same as the input | The same table |
Ask two questions. Do I need to keep every row? Does the extra information live in the same table or another one?
One task, three shapes
Take a sales table and compute the total per region.
import polars as pl
df = pl.DataFrame({
"region": ["east", "east", "west", "west", "west"],
"product": ["a", "b", "a", "b", "b"],
"sales": [10, 20, 5, 15, 25],
})
# One row per region: 2 rows
summary = df.group_by("region").agg(
pl.col("sales").sum().alias("total")
).sort("region")
# Every row kept, total repeated: 5 rows
windowed = df.with_columns(
pl.col("sales").sum().over("region").alias("total")
)
# group_by followed by join gives the same result as over: 5 rows
joined = df.join(summary, on="region", how="left")
print(summary.shape, windowed.shape, joined.shape) # (2, 2) (5, 4) (5, 4)windowed and joined hold the same values. over does the work in one expression and needs no second table. The group_by plus join route builds the summary first and then attaches it to the original rows.
When each one fits
Use group_by when the summary is the final answer, such as a report with one line per region.
Use over when you want a per-group value beside the original detail, such as each row's share of its region total:
shares = df.with_columns(
(pl.col("sales") / pl.col("sales").sum().over("region")).alias("share")
)Use join when the data lives in a different table, or when you need a summary that over cannot express. An example is a summary built from filtered rows or from a different grain, which you then attach to the detail rows. In that case, build the summary with group_by and join it back.
Common mistakes
- Using
group_byand then trying to recover the detail rows. If you need both, useover. - Joining a table to a summary of itself when
overwould do. The join adds a step and a possible key mismatch. - Expecting
overto bring in columns from another table. It only sees the current DataFrame.
Exercise
You have an orders table and a separate customers table. You want every order with the customer's name attached, keeping orders whose customer is missing. Which tool do you use, and with which options?
Show answer
Use a join, because the name lives in another table. Call orders.join(customers, on="customer_id", how="left") so unmatched orders are kept with a null name. over cannot help because it only uses columns in the same DataFrame.