Sub topic 9
Per-group values on every row with over
This chapter assumes you can build a Polars DataFrame, select columns with pl.col, and use group_by with agg as covered earlier. The goal is to compute a per-group value, such as a total or a mean, and put it next to every original row without collapsing the table.
The problem over solves
group_by("region").agg(...) returns one row per group. That is the right shape for a summary table. Often you want something different: keep all rows and add a column that says "the total for this row's region". Without a window expression you would aggregate, then join the result back on the key. over does both steps in one expression.
A window expression is an expression evaluated within groups of rows, where the result has the same height as the input. In Polars you create one by adding .over(...) to an expression.
The examples use this DataFrame throughout:
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],
})The basic pattern
Take an aggregation, then call over with the column that defines the groups:
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) # still 5 rows; region_total is 30 for east rows and 45 for west rowsHere is what happens for each over call:
- Polars splits the rows into groups by
region. - It evaluates
pl.col("sales").sum()inside each group, giving one value per group. - It writes that value back onto every row of that group, in the original row positions.
The share column shows why this is useful. Each row's sales are divided by its own region's total, so east gives 10/30 and 20/30, and west gives 5/45, 15/45 and 25/45.
over compared with group_by plus join
The same result can be built by aggregating and joining back:
totals = df.group_by("region").agg(pl.col("sales").sum().alias("region_total"))
out = df.join(totals, on="region", how="left")Both produce the same values. The over version is shorter and has no intermediate table or join key to manage. It also keeps the input's row order. Prefer group_by plus join when you need the group summary table for its own sake, or when the lookup table comes from a different source.
Where the window expression can appear
You can use a window expression anywhere an expression is allowed. In with_columns it adds columns. In select it returns only the columns you name. In filter it lets you keep rows based on a group-level fact:
above_avg = df.filter(
pl.col("sales") > pl.col("sales").mean().over("region")
)
print(above_avg) # east/b/20 and west/b/25Both regions have a mean of 15, so only the rows with sales above 15 stay. The row with sales of 15 in west is equal to the mean, not greater, so it is dropped. Filtering by a group statistic is awkward with group_by alone, and over handles it directly.
Deviation from the group mean is another common use:
out = df.with_columns(
(pl.col("sales") - pl.col("sales").mean().over("region")).alias("vs_mean")
)
print(out) # vs_mean: -5.0, 5.0, -10.0, 0.0, 10.0Grouping by more than one column
Pass several column names to over. Rows share a group only if they match on all of them:
out = df.with_columns(
pl.col("sales").sum().over("region", "product").alias("region_product_total")
)
print(out) # 10, 20, 5, 40, 40The two west/b rows form one group, so both get 15 + 25 = 40. You can also pass a list, such as over(["region", "product"]), which means the same thing. Group keys can be expressions too, for example over(pl.col("region").str.to_lowercase()).
Counting rows and conditional totals
Any aggregation works inside over. pl.len() gives the group size:
out = df.with_columns(
pl.len().over("region").alias("rows_in_region")
)
print(out) # 2, 2, 3, 3, 3For a conditional total that is still shown on every row, put the condition inside the aggregated expression with when/then:
out = df.with_columns(
pl.when(pl.col("product") == "b")
.then(pl.col("sales"))
.otherwise(0)
.sum()
.over("region")
.alias("b_sales_in_region")
)
print(out) # 20, 20, 40, 40, 40The when expression builds a column that holds sales for product b and 0 otherwise. The sum and over then total that column per region.
Applying one window to several columns
Column selectors expand into several expressions, and over applies to each of them:
df2 = pl.DataFrame({
"region": ["east", "east", "west"],
"units": [1, 2, 3],
"sales": [10, 20, 30],
})
out = df2.with_columns(
pl.col("units", "sales").sum().over("region").name.suffix("_total")
)
print(out) # units_total: 3, 3, 3; sales_total: 30, 30, 30Without name.suffix (or alias), the output would reuse the input column names and overwrite them. That is the usual behavior of with_columns: a result with an existing name replaces the old column.
Common errors
- Forgetting over.
pl.col("sales").sum()inwith_columnscomputes one value for the whole table and repeats it on every row. The code runs without error and produces a plausible but wrong column. - Expecting fewer rows.
overnever reduces the row count. If you want one row per group, usegroup_by. - Expecting a result that is the wrong length. The expression before
overmust return either a single value per group, which Polars repeats, or one value per row of the group, which is the case for ranking and cumulative sums covered in the next chapter. Other lengths raise an error under the default settings. - Null group keys. Rows with a null in the key column form their own group. They are not dropped. Filter nulls out first if you do not want them treated as a group.
- Overwriting a column by accident. If you do not call
alias, the output takes the name of the root column and replaces it.
Summary
over turns an aggregation into a window expression. It computes the value once per group and places it on each row of that group, so the DataFrame keeps its height and row order. Use it for shares, deviations from a group mean, group sizes, and filters based on group statistics. Reach for group_by instead when you want one output row per group.
Exercise
Using the df from this chapter, write a withcolumns call that adds a column named "maxinregion" holding the highest sales value in each row's region, and a second column named "gaptomax" holding the difference between that maximum and the row's own sales. What are the values of gapto_max, and how many rows does the result have?
Show answer
out = df.withcolumns(pl.col("sales").max().over("region").alias("maxinregion")).withcolumns((pl.col("maxinregion") - pl.col("sales")).alias("gaptomax")). The east maximum is 20 and the west maximum is 25, so gaptomax is 10, 0, 20, 10, 0. The result has 5 rows, the same as the input, because over keeps every row. Both columns can also be built in one withcolumns call by writing (pl.col("sales").max().over("region") - pl.col("sales")).alias("gapto_max").
Exercise
A colleague writes df.with_columns(pl.col("sales").mean().alias("avg")) and says it gives the average sales per region. What does it actually compute, and how do you fix it?
Show answer
It computes the mean of the whole sales column, which is 15.0, and repeats that value on all 5 rows. There is no grouping, so every region gets the same number. The fix is to add over: pl.col("sales").mean().over("region").alias("avg"). For this data both regions happen to have a mean of 15.0, so test with different data to see the difference.