Sub topic 9
Per-group values on every row with over
This chapter assumes you can create a Polars DataFrame, select columns with pl.col, and use group_by with agg. Here you will learn how over computes a per-group value and keeps every row.
The problem: summaries that lose rows
group_by(...).agg(...) returns one row per group. Sometimes you need the group total next to each original row, for example to compute each row's share of its group. You could aggregate and then join the result back. over does this in one expression.
How over works
over turns an aggregation into a window expression. Polars computes the value separately for each group, then repeats it on every row of that group. The DataFrame keeps its original height.
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],
})
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 rowsThe east rows get region_total 30 and the west rows get 45. The share column divides each row's sales by its own group's total.
Use over inside a context
over belongs in with_columns or select. These contexts keep one output value per input row, which is the shape a window expression produces. Inside agg, you would normally use a plain aggregation instead.
You can pass several columns to partition by more than one key:
out = df.with_columns(
pl.col("sales").sum().over("region", "product").alias("region_product_total")
)
print(out)Rows with the same region and product share a total. For example, both west / b rows get 40.
Common errors
- Forgetting
over.pl.col("sales").sum()insidewith_columnscomputes one total for the whole column and broadcasts it to every row. The result has no per-group values and raises no error. - Expecting fewer rows.
overnever drops or collapses rows. If you want one row per group, usegroup_by. - Using
overfor a filter. Combiningoverwithfilterworks, but a boolean expression such aspl.col("sales") == pl.col("sales").max().over("region")is usually clearer. It marks the best row in each region.
top = df.filter(pl.col("sales") == pl.col("sales").max().over("region"))
print(top) # the largest-sales row in each regionHere over computes each region's maximum on every row. filter then keeps the rows that match it, so you get the top row per region without a join.
Summary
overmakes an aggregation per-group and keeps all rows.- Use it in
with_columnsorselect. - Pass several columns to
overto partition by a combined key.
Exercise
Using the df above, add a column named "maxsales" holding the largest sales value in each product, on every row. How many rows does the result have, and what is maxsales for the rows where product is "a"?
Show answer
Use df.withcolumns(pl.col("sales").max().over("product").alias("maxsales")). The result has 5 rows. For product "a" the sales are 10 and 5, so max_sales is 10 on both of those rows.