Sub topic 15
Choosing between group_by, join, and over
This chapter assumes you can write select, with_columns, and agg expressions, and that you know the basics of group_by, joins, and over. Here you will compare the three tools and pick one for a given task.
Start from the shape you need
All three tools combine rows that share a key. They differ in what the result looks like.
| Tool | Input | Result height | Typical use |
|---|---|---|---|
| `group_by(...).agg(...)` | One frame | One row per group | Reports, summaries |
| `join` | Two frames | Depends on the join type and key matches | Adding columns from another table, filtering by membership |
| `expr.over(...)` | One frame | Same as the input | Per-group values next to row-level values |
Ask these questions in order:
- Does the data live in one frame or two? Two frames means a join.
overandgroup_bycannot see another frame. - Do you want to keep every input row? If yes, use
overor a join. If you want one row per group, usegroup_by. - Does the result depend on row order within each group (rank, running total, previous value)? Use
overwith an order-dependent expression.
One problem, two solutions
Suppose you want each sale as a share of its region's total. The data is in one frame, and you want every row kept. The tutorial's sales frame is reused here, with a row index added so the output can be compared reliably.
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],
}).with_row_index("id")
# Solution 1: aggregate, then join the totals back
totals = df.group_by("region").agg(pl.col("sales").sum().alias("region_total"))
via_join = (
df.join(totals, on="region", how="left")
.with_columns((pl.col("sales") / pl.col("region_total")).alias("share"))
.sort("id")
)
# Solution 2: one window expression
via_over = df.with_columns(
pl.col("sales").sum().over("region").alias("region_total"),
(pl.col("sales") / pl.col("sales").sum().over("region")).alias("share"),
)
print(via_join)
print(via_over)
print(via_join.equals(via_over)) # TrueBoth produce five rows with the same values: east rows have region_total 30, and west rows have 45. Solution 2 is shorter and cannot go wrong through a mismatched key. over is effectively the "group_by, then join back" pattern packaged as one expression. Prefer it when the aggregate and the rows come from the same frame.
The explicit version still has uses. If totals is reused in several places, or is itself a report you want to output, building it once is clearer than repeating over.
When group_by is the right tool
Use group_by when the group is the unit of output. Each group collapses to one row, and the other rows are not needed.
report = (
df.group_by("region")
.agg(
pl.col("sales").sum().alias("total"),
pl.len().alias("rows"),
pl.col("sales").filter(pl.col("product") == "b").sum().alias("b_sales"),
)
.sort("region")
)
print(report) # east: 30, 2, 20; west: 45, 3, 40Using over here would produce five rows with repeated values, and you would then need unique to get back to two. That works but is a sign you picked the wrong tool.
Two gotchas apply to group_by:
- Group order is not guaranteed. Sort the result, or pass
maintain_order=Truewhen you need groups in order of first appearance. That option costs some speed. - Within
agg, an expression that returns more than one value per group produces a list in that cell. This is often a sign that you wantedover, or that you forgot to reduce the values withsum,first, or similar.
When join is the right tool
Use a join when the extra information lives in another frame, or when you need to test membership. over cannot do either.
targets = pl.DataFrame({
"region": ["east", "west", "north"],
"target": [25, 50, 40],
})
summary = (
df.group_by("region")
.agg(pl.col("sales").sum().alias("total"))
.join(targets, on="region", how="full", coalesce=True)
.sort("region")
)
print(summary)
# east: total 30, target 25
# north: total null, target 40
# west: total 45, target 50This example uses both tools in sequence. group_by reduces the sales to one row per region, and the full join then brings in north, which has targets but no sales. With coalesce=True, the key columns are merged into one region column. Without it, you would get a separate region_right column.
Choose the join type by what should happen to unmatched rows:
leftkeeps every left row and fills missing right values with null.innerkeeps only matches.antireturns left rows with no match, which is useful for finding missing keys.semireturns left rows that have a match, without adding right columns. It filters by membership and avoids duplicating rows when the right side has repeated keys.
Joins are the one tool of the three that can change your row count unexpectedly. If the right table has two rows for a key, each left row with that key appears twice. After you build a lookup table, check that its key is unique. The validation options from the earlier join chapter (validate="m:1", for example) turn this mistake into an error.
When over is the right tool
Use over when each output row needs a value computed from its group, and every input row must survive. Common cases:
- Normalizing a value against its group (share of total, difference from the group mean).
- Ranking, shifting, or accumulating inside groups.
- Filtering rows by a group-level condition.
The last case is where over is most convenient. To keep the top sale in each region, with all its columns intact:
top = df.filter(pl.col("sales") == pl.col("sales").max().over("region"))
print(top) # east: product b, sales 20; west: product b, sales 25The group_by equivalent needs an aggregation that picks whole rows (such as pl.all().sort_by("sales").last()), or a group_by followed by a join back. The over version states the condition directly. Note that ties keep every tied row, which may not be what you want. If you need exactly one row per group, use group_by.
For order-dependent work, over evaluates the expression separately for each group:
out = df.with_columns(
pl.col("sales").cum_sum().over("region").alias("running_total"),
pl.col("sales").shift(1).over("region").alias("previous"),
)
print(out) # running_total restarts at each region; previous is null for the first row of each regionRows are processed in their current frame order within each group, so sort first if the meaning depends on time.
Edge cases that decide close calls
- Null keys.
group_byandovertreat null as its own group. Joins do not match null keys to each other by default, so a row with a null key appears unmatched. Your group-by-then-join workaround can therefore lose rows thatoverwould keep. Check the null-handling option for your Polars version if you need nulls to match. - Row order.
overreturns rows in the original order. A join does not promise an order unless you request one or sort afterward, which is why the first example sorts byid.group_bydoes not promise an order either. - Cost.
overwith many distinct groups and many columns is usually comparable to group-by plus join. Measure on your data before choosing for speed. Choose for clarity first. - Mixed aggregations. When some outputs should be per group and others per row, put everything in one
with_columnswith severalovercalls. That is one pass of code and one frame.
Running the choice lazily
All three tools work the same way on a LazyFrame. Call lazy() on the frame, build the same expressions, and call collect() at the end. Because over is a single expression, you do not name an intermediate frame, and the engine sees the whole query when it plans execution.
Exercise
You have an orders frame with customer_id and amount, and you need a column pct_of_customer showing each order's amount as a fraction of that customer's total spending. All rows must remain. Which tool do you use, and what is the expression?
Show answer
Use over, because the data is in one frame and every row must stay. For example: orders.with_columns((pl.col("amount") / pl.col("amount").sum().over("customer_id")).alias("pct_of_customer")).
Exercise
You need the list of orders whose customer_id is missing from a customers table. Why can neither group_by nor over do this, and which join type do you use?
Show answer
Both group_by and over work on a single frame and cannot see customers. Use an anti join: orders.join(customers, on="customer_id", how="anti") returns only the orders without a matching customer.