Sub topic 10
Per-group values with over()
This chapter shows how to compute a value per group and attach it to every row, without collapsing the DataFrame. It assumes you can already write expressions with pl.col, use select and with_columns, and run group_by(...).agg(...). The examples use the same small DataFrame as the earlier chapters.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)The problem over() solves
group_by("dept").agg(...) returns one row per group. Often you need the group-level number next to each original row. Examples are comparing each salary to its department average, or keeping only the top earner in each department.
A window expression does this. You write an ordinary expression, then call .over(...) on it with the columns that define the groups. Polars computes the expression separately inside each group and maps the results back to the original rows. The row count and row order do not change.
df2 = df.with_columns(
pl.col("salary").mean().over("dept").alias("dept_avg"),
)
print(df2)dept_avg is 110.0 for Ana and Ben, and 85.0 for Cy and Dee. All four rows are still there.
How over() works
For each group, Polars evaluates the expression on only that group's rows. It then places the result back at the positions those rows occupy in the original frame.
flowchart LR
A[Original rows] --> B[Split by dept]
B --> C[eng rows: compute mean]
B --> D[ops rows: compute mean]
C --> E[Map result back to eng row positions]
D --> F[Map result back to ops row positions]
E --> G[Same rows plus new column]
F --> GThe diagram block below is the same diagram in the required form.
What happens when the results are mapped back depends on what the expression returns for each group:
- If it returns a single value (a scalar, such as
mean()ormax()), that value is repeated for every row in the group. This is called broadcasting. - If it returns one value per row (such as
rank()orcum_sum()), the values are written back row by row, in the order the group's rows had in the original frame.
Common window patterns
Compare each row to its group
Because over is part of an expression, you can use the result in arithmetic.
diff = df.with_columns(
(pl.col("salary") - pl.col("salary").mean().over("dept")).alias("vs_avg")
)
print(diff)Ana gets 10.0, Ben gets -10.0, Cy gets -5.0 and Dee gets 5.0.
Rank within each group
rank returns one value per row, so each group gets its own ranking.
ranked = df.with_columns(
pl.col("salary")
.rank(method="ordinal", descending=True)
.over("dept")
.alias("rank_in_dept")
)
print(ranked)Ana and Dee get rank 1. Ben and Cy get rank 2. The ordinal method gives every row a distinct rank, even when salaries tie.
Filter by a group property
filter is a context, and it accepts expressions that use over. This keeps the highest-paid person in each department:
top = df.filter(pl.col("salary") == pl.col("salary").max().over("dept"))
print(top)The result is Ana and Dee. The max().over("dept") part produces a full-length column of per-department maxima, and the comparison turns it into a boolean mask.
Running totals
Expressions such as cum_sum depend on row order, so the order within each group matters.
running = df.with_columns(
pl.col("salary").cum_sum().over("dept").alias("running_total")
)
print(running)Within eng the totals are 120 and 220. Within ops they are 80 and 170. The cumulative sum restarts for each group.
Several grouping keys
Pass more than one column to group by their combination. This example reuses the band idea from the conditional chapter.
df3 = (
df.with_columns(
pl.when(pl.col("salary") >= 100)
.then(pl.lit("high"))
.otherwise(pl.lit("standard"))
.alias("band")
)
.with_columns(
pl.len().over("dept", "band").alias("same_dept_and_band")
)
)
print(df3)Ana and Ben share eng and high, so both get 2. Cy and Dee share ops and standard, so both also get 2.
over() versus group_by()
| Question | `group_by().agg()` | `expr.over()` |
|---|---|---|
| Rows returned | One per group | Same as input |
| Original columns kept | No, only keys and aggregates | Yes |
| Row order | Not guaranteed unless you sort or use `maintain_order=True` | Preserved |
| Typical use | Summary tables | Adding group context to rows, filtering by group |
If you only need a summary, use group_by. If you need to keep the detail rows, use over. The alternative to over is a group_by followed by a join back on the key. That works, but it is longer and does more work.
Mapping strategies
The mapping_strategy argument controls how group results go back into the frame. The default is "group_to_rows", which is the behavior shown above.
The "join" strategy keeps one row per input row, but each row holds the whole group result as a list:
joined = df.with_columns(
pl.col("salary").over("dept", mapping_strategy="join").alias("dept_salaries")
)
print(joined)Ana and Ben each get [120, 100]. Cy and Dee each get [80, 90].
The "explode" strategy returns the group results as flat rows, laid out group by group. It is faster, because Polars skips the step of mapping values back to the original positions. The cost is that the new column no longer lines up with the original row order, so do not combine it with other columns of the original frame unless you have checked the alignment.
Edge cases and pitfalls
- Null keys. Rows whose key is null form their own group. They are not dropped.
- Null values. Aggregations such as
meanskip null values within each group, the same as they do in a plainselect. - The key column is not required in the output.
overonly reads the grouping columns. You do not need to select them. - Order-dependent expressions.
cum_sum,shiftandfirstfollow the current row order inside each group. Sort the frame first, or usesort_byinside the expression, when order matters. - A scalar is not a window.
pl.col("salary").mean()withoutoverreturns the global mean, so every row gets the same value. A missing.over(...)is a common cause of numbers that look right but are wrong. - Cost. Each distinct set of keys requires a grouping step. If you use
.over("dept")in five expressions inside onewith_columns, Polars can reuse the grouping, but separatewith_columnscalls may repeat it. Put related window expressions in the same call.
Summary
A window expression is a normal expression plus .over(keys). It computes the expression per group and puts the answer back on every original row, so the frame keeps its shape. Use it for comparisons with group statistics, ranks, running totals and group-based filters. Use group_by when you want a summary table.
Exercise
Using the DataFrame from this chapter, write an expression that adds a column pct_of_dept with each person's salary as a fraction of their department's total salary. What is Ben's value?
Show answer
df.with_columns((pl.col("salary") / pl.col("salary").sum().over("dept")).alias("pct_of_dept")). The eng total is 120 + 100 = 220, so Ben's value is 100 / 220, about 0.4545.
Exercise
You want to keep only the lowest-paid person in each department. Write the filter, and say which rows remain.
Show answer
df.filter(pl.col("salary") == pl.col("salary").min().over("dept")). The eng minimum is 100 and the ops minimum is 80, so Ben and Cy remain.
Exercise
A colleague writes df.with_columns(pl.col("salary").mean().alias("dept_avg")) and gets 97.5 in every row. What is missing, and what values would the fix produce?
Show answer
The expression has no .over("dept"), so the mean is taken over the whole column (97.5). The fix is pl.col("salary").mean().over("dept"), which gives 110.0 for Ana and Ben and 85.0 for Cy and Dee.