Sub topic 10
Ranking, shifting, and cumulative values within groups
This chapter assumes you know with_columns, pl.col, and the basic form of over from the previous chapter. You should also know that over keeps the original row count.
Order-dependent expressions inside groups
Some expressions depend on row order or on the other values in a column. Examples are rank, shift, and cum_sum. Without over, they treat the whole column as one sequence. With over("region"), Polars evaluates them separately for each group and writes the results back to the original rows.
The examples below use this DataFrame:
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],
})Ranking within a group
rank assigns each value a position. The method argument controls how ties are handled, and descending=True gives rank 1 to the largest value.
out = df.with_columns(
pl.col("sales").rank(method="dense", descending=True).over("region").alias("rank_in_region"),
pl.col("sales").cum_sum().over("region").alias("running_total"),
)
print(out) # east ranks: 2, 1; west ranks: 3, 2, 1; running totals restart per regionThe rank restarts at 1 in each region. The running total restarts too. East accumulates 10 then 30, and west accumulates 5, 20, then 45.
Shifting and differences
shift(n) moves values down by n rows and fills the gap with null. Inside over, the shift never crosses a group boundary, so the first row of each group is always null.
out = df.with_columns(
pl.col("sales").shift(1).over("region").alias("prev_sales"),
(pl.col("sales") - pl.col("sales").shift(1)).over("region").alias("change"),
)
print(out)The prev_sales column holds null, 10, null, 5, 15. The change column holds null, 10, null, 10, 10. Note that over wraps the whole arithmetic expression in the second line, so both sales and its shifted copy are evaluated per group.
Row order matters
These expressions use the order the rows already have in the DataFrame. over does not sort anything. If your data is not in time order, sort first, or you will get shifts and running totals in the wrong order.
out = (
df.sort("sales")
.with_columns(pl.col("sales").cum_sum().over("region").alias("running_total"))
)sort is a separate step from over. Use it when the order you want differs from the stored order.
Common errors
| Symptom | Likely cause |
|---|---|
| Running total continues across groups | `over` was left off |
| `shift` gives wrong neighbours | Rows are not sorted in the order you intended |
| Rank 2 appears twice and rank 3 is skipped | Default `average` is not in use; `min` leaves gaps, `dense` does not |
| Unexpected null in the first row | Expected: `shift` has nothing earlier to read |
Picking the top row per group
A rank column makes it easy to keep only the best rows. Filter on the ranking expression directly:
top = df.filter(
pl.col("sales").rank(method="ordinal", descending=True).over("region") == 1
)
print(top) # one row per region: east 20, west 25Here ordinal guarantees a unique rank even when values tie, so exactly one row per region survives.
Exercise
Using the DataFrame above, write an expression that adds a column pct_of_running giving each row's sales divided by the running total of sales in its region. What are the values for the west rows?
Show answer
df.withcolumns((pl.col("sales") / pl.col("sales").cumsum().over("region")).alias("pctofrunning")). Since over only applies to cum_sum, the division happens on whole columns and still works row by row. The west running totals are 5, 20, 45, so the values are 5/5 = 1.0, 15/20 = 0.75, and 25/45 ≈ 0.556.