Sub topic 10
Ranking, shifting, and cumulative values within groups
The previous chapter introduced over, which computes a per-group value and keeps every row. This chapter uses over with expressions that depend on row order or position: rank, shift, diff, and the cum_* family. This is the main way to answer "where does this row stand inside its group?" without collapsing the table.
This chapter assumes you can write with_columns and aggregation expressions, and that you know expr.over("key") repeats a group value on each row.
What changes with order-dependent expressions
sum().over("region") returns one value per group, which Polars repeats on each row. rank(), shift(), and cum_sum() return one value per row. Polars still splits the data by group, runs the expression on each piece, and writes the results back to the original row positions.
The shape is the same as for aggregations, but the result differs per row. The expression sees only one group's values at a time, so a running total restarts in each group and a shift never pulls a value across a group boundary.
Ranking within groups
rank assigns each value its position in sorted order. By default it ranks ascending. Pass descending=True so the largest value gets rank 1.
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").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 regionChoosing a tie method
The method argument decides what happens when values are equal. The default, "average", returns floats, which surprises people who expect integer ranks. The other methods return integers.
For the values [10, 10, 5] ranked descending:
| method | result | meaning |
|---|---|---|
| `average` | 1.5, 1.5, 3.0 | tied rows share the mean of their positions |
| `min` | 1, 1, 3 | tied rows get the lowest position, and a gap follows |
| `max` | 2, 2, 3 | tied rows get the highest position |
| `dense` | 1, 1, 2 | tied rows share a rank and no gap follows |
| `ordinal` | 1, 2, 3 | every row gets a distinct rank, ties broken by row order |
Use ordinal when you need exactly N rows per group. Use dense or min when equal values should count as equal.
Top N per group
A window expression can be used directly inside filter. This keeps the two best-selling rows in each region:
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],
})
top2 = df.filter(
pl.col("sales").rank(method="ordinal", descending=True).over("region") <= 2
)
print(top2) # east: 10 and 20; west: 15 and 25 (the 5 is dropped)The result keeps the original row order. ordinal guarantees at most two rows per region even if sales values tie. With min, a three-way tie for first place would return three rows.
Shifting and differences
shift(n) moves values down by n rows, so each row sees the value from n rows earlier. A negative n looks ahead. The vacated positions are filled with null, or with fill_value if you pass one. diff() is the current value minus the previous one, and it is equivalent to x - x.shift(1).
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").shift(1).over("region").alias("prev_sales"),
pl.col("sales").diff().over("region").alias("change"),
pl.col("sales").shift(-1).over("region").alias("next_sales"),
)
print(out)
# prev_sales: null, 10, null, 5, 15
# change: null, 10, null, 10, 10
# next_sales: 20, null, 15, 25, nullThe first row in each region has no predecessor, so it gets null. This is the point of using over.
The most common mistake: leaving out over
Without over, the expression treats the whole column as one sequence:
import polars as pl
df = pl.DataFrame({
"region": ["east", "east", "west", "west", "west"],
"sales": [10, 20, 5, 15, 25],
})
wrong = df.with_columns(pl.col("sales").shift(1).alias("prev_sales"))
print(wrong) # the first west row shows prev_sales 20, which belongs to eastPolars raises no error here. The first west row now reports an east value as its predecessor. Whenever a shift, diff, or cumulative column is meant to be per group, check that over is attached.
Cumulative values
The cum_* expressions compute a running result from the first row to the current one:
cum_sum()is a running total.cum_max()andcum_min()track the highest or lowest value so far.cum_count()numbers the rows seen so far.cum_prod()is a running product.
Each takes reverse=True to accumulate from the last row backward. Combine them with other expressions to get ratios, such as each row's running share of its group total:
import polars as pl
df = pl.DataFrame({
"region": ["east", "east", "west", "west", "west"],
"sales": [10, 20, 5, 15, 25],
})
out = df.with_columns(
(
pl.col("sales").cum_sum().over("region")
/ pl.col("sales").sum().over("region")
).alias("cumulative_share"),
pl.col("sales").cum_max().over("region").alias("best_so_far"),
)
print(out) # east cumulative_share: 0.333..., 1.0; west: 0.111..., 0.444..., 1.0Two window expressions in one formula are independent. Each is partitioned by region on its own, so you can mix a cumulative expression and a full-group aggregate.
Row order decides the result
Shift, diff, and cumulative expressions follow the order of rows inside each group. They do not sort anything. If your data is in arbitrary order, the "previous" row is just whichever row comes earlier in the table.
There are two ways to fix this. The first is to sort the DataFrame before the window expression. The second, available in recent Polars versions, is to pass order_by to over. Polars then evaluates the expression in that order and still returns the results in the original row positions:
import polars as pl
df = pl.DataFrame({
"region": ["east", "east", "west", "west"],
"day": [2, 1, 2, 1],
"sales": [20, 10, 15, 5],
})
out = df.with_columns(
pl.col("sales").cum_sum().over("region", order_by="day").alias("running_total")
)
print(out) # running_total: 30, 10, 20, 5 (row order is unchanged)The day-2 east row shows 30 because it comes after the day-1 row in time, even though it appears first in the table. If order_by raises an error in your installed version, sort first with df.sort("region", "day") and then use plain over("region").
Edge cases to remember
- Ranking descending puts the largest value at rank 1. Ascending is the default.
- Nulls in a ranked column are not given a numeric rank, so check how your data handles them before filtering on rank.
shiftchanges values but never row count, so the output height always equals the input height.- Several columns can be partitioned together with
over("region", "product"), which creates one group per combination.
Exercise
Given the DataFrame with columns region and sales used in this chapter, write an expression that adds a column called gain holding each row's sales minus the previous row's sales within the same region, and explain why the first row of each region shows null.
Show answer
Use pl.col("sales").diff().over("region").alias("gain"), or equivalently (pl.col("sales") - pl.col("sales").shift(1)).over("region"). The first row of each region has no earlier row in its group, so the shifted value is null and the difference is null. Without over, the first west row would instead be compared with the last east row.
Exercise
You want exactly the three highest-selling rows in each region, even when sales values tie. Which rank method do you pass, and where do you put the comparison?
Show answer
Use rank(method="ordinal", descending=True).over("region") <= 3 inside df.filter(...). Ordinal ranking gives each row a distinct rank, so at most three rows per region survive. The "min" method could keep more than three rows when values tie.