Sub topic 2
Summarizing groups with group_by and agg
This chapter assumes you know basic Python syntax, can read tabular data (rows, columns, keys), and can create a Polars DataFrame and select columns with pl.col. It also builds on the idea that an expression describes a computation and a context decides where it runs.
What group_by does
group_by splits a DataFrame into groups of rows that share the same key value. agg then runs expressions on each group and returns one row per group. The result has the key columns first, followed by one column per expression.
A first example
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.group_by("region").agg(
pl.col("sales").sum().alias("total"),
pl.len().alias("rows"),
).sort("region")
print(out) # east: total 30, rows 2; west: total 45, rows 3Each argument to agg is an expression. pl.col("sales").sum() reduces the sales values of one group to a single number. pl.len() counts the rows in the group. alias names the output column. Without it, the column keeps the name sales, and two expressions on the same column would clash.
Polars runs the expressions in agg in parallel across groups, so passing several expressions in one call is cheaper than calling group_by repeatedly.
Why sort
Group order is not guaranteed by default. Two runs on the same data can return groups in different orders. The .sort("region") call makes the output deterministic. The next chapters cover maintain_order for the case where you want groups in order of first appearance.
Grouping by several keys
Pass a list to group by a combination of columns. Each unique pair becomes one group.
out = df.group_by("region", "product").agg(
pl.col("sales").sum().alias("total")
).sort("region", "product")
print(out) # four rows: east/a, east/b, west/a, west/bThe west/b group combines two source rows (15 and 25), so its total is 40.
Common aggregations
| Expression | Result per group |
|---|---|
| `pl.col("sales").sum()` | Total of the values |
| `pl.col("sales").mean()` | Average |
| `pl.col("sales").max()` | Largest value |
| `pl.col("sales").n_unique()` | Count of distinct values |
| `pl.col("product").first()` | First value in the group |
| `pl.len()` | Number of rows |
Common errors
- Forgetting to reduce.
pl.col("sales")alone insideaggdoes not fail. It returns a list of all the group's values in one cell. This is occasionally useful, but usually it means you forgot.sum()or a similar call. - Using the old name. Older tutorials call
groupby. Current Polars usesgroup_by. - Relying on row order. Without
sort, tests that compare output can pass on one run and fail on the next. - Expecting the original rows back.
group_byshrinks the DataFrame to one row per group. If you need the group value on every original row, useover, which a later chapter covers.
Exercise
Given the DataFrame above, write a group_by that returns, for each product, the average sales and the number of rows, sorted by product. What does the row for product "b" contain?
Show answer
Use df.groupby("product").agg(pl.col("sales").mean().alias("avgsales"), pl.len().alias("rows")).sort("product"). Product "b" has sales 20, 15 and 25 across three rows, so avg_sales is 20.0 and rows is 3.