Sub topic 3
Ranking, Shifting, and Cumulative Values Within Groups
Assume basic Python, tabular data, and pl.col. In Polars, a window expression calculates within groups while keeping the original rows.
Ranking, shifting, and cumulative values
Use over("region") to restart an operation for each region. The input order matters for shift and cum_sum, so sort first when order has meaning.
import polars as pl
df = pl.DataFrame({
"region": ["east", "east", "west", "west", "west"],
"sales": [10, 20, 5, 15, 25],
})
out = df.sort(["region", "sales"]).with_columns(
pl.col("sales").rank("dense", descending=True)
.over("region")
.alias("rank"),
pl.col("sales").shift(1).over("region").alias("previous"),
pl.col("sales").cum_sum().over("region").alias("running_total"),
)
print(out)The rank restarts in every group. The first value of previous is null. The cumulative total also restarts for each region.
Window mapping strategies
Polars maps each group result back to rows. The default group_to_rows strategy preserves the input height and row positions. join produces list values for each group. explode returns group results in grouped order and can change row ordering. Use the default when each result corresponds to one input row.
Rolling window expressions
A rolling expression uses nearby ordered rows. This three-row mean needs two earlier values before producing a result:
daily = pl.DataFrame({"sales": [10, 20, 30, 40, 50]})
out = daily.with_columns(
pl.col("sales").rolling_mean(window_size=3).alias("avg_3")
)The first two avg_3 values are null because the window is incomplete.
Time-bucketed aggregation
group_by_dynamic places sorted timestamps into fixed intervals.
out = events.group_by_dynamic("ts", every="1d").agg(
pl.col("value").sum().alias("daily_total")
)Matching earlier records
join_asof matches each left row with the latest right row at or before its key. Both inputs must be sorted by that key. This is useful for applying the latest known price, status, or configuration.
Choosing the operation
- Use
group_by(...).agg(...)when the result should have one row per group. - Use
joinwhen you need columns from another table. - Use
over(...)when every original row must remain.
Running lazily
Lazy frames build a query plan before execution. Replace pl.read_parquet with pl.scan_parquet, compose grouping, joining, and window expressions, then call .collect(). Polars can optimize the complete plan before reading data.
Exercise
Which operation should calculate each order's percentage of its region total while keeping every order?
Show answer
Use over("region"), such as sales / sales.sum().over("region").