Sub topic 10
Replacing transform with over
This chapter assumes you know pandas groupby().transform() and have read the earlier chapters on expressions and group by. Here you will learn how Polars over computes a per-group value for every row without collapsing the frame.
What transform does and what over replaces
In pandas, groupby().transform() returns a Series with the same length as the input. Each row receives the result computed for its group. You use it to add a group mean, a group rank, or a share of the group total.
In Polars, you write the expression as if it ran on the whole column, then append .over("key"). Polars computes the expression per group and maps the result back to the original rows. The frame keeps its length and row order.
import numpy as np
import pandas as pd
import polars as pl
data = {
"region": ["east", "east", "west", "west", "west"],
"total": [50.0, 150.0, 80.0, 120.0, 200.0],
}
# pandas
pdf = pd.DataFrame(data)
pdf["region_mean"] = pdf.groupby("region")["total"].transform("mean")
pdf["size"] = np.where(pdf["total"] > 100, "large", "small")
# Polars
df = pl.DataFrame(data).with_columns(
pl.col("total").mean().over("region").alias("region_mean"),
pl.when(pl.col("total") > 100)
.then(pl.lit("large"))
.otherwise(pl.lit("small"))
.alias("size"),
)
print(df)The when/then/otherwise chain replaces np.where and conditional assignment. It is an expression, so it can sit inside with_columns next to the over expression.
Common window patterns
Because over accepts any expression, one syntax covers several pandas idioms.
| Goal | pandas | Polars |
|---|---|---|
| Group mean on each row | `transform("mean")` | `pl.col("x").mean().over("g")` |
| Share of group total | `x / g["x"].transform("sum")` | `pl.col("x") / pl.col("x").sum().over("g")` |
| Rank within group | `groupby("g")["x"].rank()` | `pl.col("x").rank().over("g")` |
| Running total in group | `groupby("g")["x"].cumsum()` | `pl.col("x").cum_sum().over("g")` |
| Previous value in group | `groupby("g")["x"].shift(1)` | `pl.col("x").shift(1).over("g")` |
You can also group by several columns by passing a list, for example .over("region", "channel").
df = df.with_columns(
(pl.col("total") / pl.col("total").sum().over("region")).alias("share"),
pl.col("total").rank(descending=True).over("region").alias("rank_in_region"),
)How over differs from group_by
group_by().agg() returns one row per group. over returns one value per input row. Use group_by when you want a summary table. Use over when you want to keep the detail rows and attach group-level context.
Common errors
- Expecting rows to be reordered. The result of
overlines up with the original row order, so you do not need to sort or realign an index as you might in pandas. - Forgetting to name the result. Without
.alias(...), the new column takes the name of the source column and overwrites it insidewith_columns. - Using
overinfilterwithout thinking. It works, for examplepl.col("total") == pl.col("total").max().over("region")keeps each group's top row. Ties keep every tied row.
Exercise
Write a Polars expression that keeps only the rows whose total equals the maximum total of their region. How many rows can it return per region?
Show answer
df.filter(pl.col("total") == pl.col("total").max().over("region")). It returns one row per region, or more than one if several rows tie for the maximum.
Exercise
A pandas line reads pdf["pct"] = pdf["total"] / pdf.groupby("region")["total"].transform("sum"). Rewrite it in Polars.
Show answer
df = df.with_columns((pl.col("total") / pl.col("total").sum().over("region")).alias("pct"))