Sub topic 10
Per-group values with over()
This chapter assumes you can build a DataFrame, write expressions with pl.col, and use group_by with agg. It also assumes you know the contexts select and with_columns.
The problem over() solves
group_by collapses each group into one row. Sometimes you want the group's value next to every original row. Examples are comparing each salary with its department average, or ranking people within a department.
A window expression does this. You write an ordinary expression, then add .over("column"). Polars computes the expression once per group and writes the result back to each row of that group. The row count does not change.
A first window expression
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
df2 = df.with_columns(
pl.col("salary").mean().over("dept").alias("dept_avg"),
pl.when(pl.col("salary") >= 100)
.then(pl.lit("high"))
.otherwise(pl.lit("standard"))
.alias("band"),
)
print(df2)The dept_avg column holds 110.0 for Ana and Ben, and 85.0 for Cy and Dee. All four rows remain. The band column comes from when/then/otherwise and does not depend on groups.
Use with_columns for window expressions. It keeps the existing columns and adds the new one.
Using the group value in further arithmetic
Because over() returns a column aligned with the original rows, you can combine it with other expressions:
result = df.with_columns(
(pl.col("salary") - pl.col("salary").mean().over("dept")).alias("diff_from_avg"),
pl.col("salary")
.rank(method="ordinal", descending=True)
.over("dept")
.alias("rank_in_dept"),
)
print(result)Ana gets a difference of 10.0 and rank 1. Ben gets -10.0 and rank 2. Cy gets -5.0 and rank 2. Dee gets 5.0 and rank 1.
Any expression that works on a column can sit before .over(). Pass several column names to group by a combination, for example .over("dept", "band").
Choosing between group_by and over
| Need | Use |
|---|---|
| One row per group | `group_by(...).agg(...)` |
| Group value on every original row | `with_columns(... .over(...))` |
| Filter rows by a group-level condition | `filter(expr.over(...))` |
The third row works because a window expression that returns booleans is valid inside filter. For example, df.filter(pl.col("salary") == pl.col("salary").max().over("dept")) keeps the top earner in each department.
Common errors
- Forgetting
.alias(...). The new column then reuses the source column's name and overwrites it. - Expecting
overto reorder rows. It does not. The original row order is kept, so you do not need to sort to align results. - Using a Python loop or
map_elementsper department.overdoes the same work natively and is much faster.
Exercise
Using the DataFrame above, write one with_columns call that adds a column pct_of_dept holding each person's salary divided by the total salary of their department.
Show answer
df.withcolumns((pl.col("salary") / pl.col("salary").sum().over("dept")).alias("pctof_dept")). Ana gets 120/220, Ben 100/220, Cy 80/170 and Dee 90/170. All four rows are kept.