Sub topic 9
Grouping and aggregating
This chapter assumes you can build a DataFrame, write expressions with pl.col, and use select, with_columns and filter. If those are new, review the earlier chapters first. Here you will learn how group_by works as a context, how to write several aggregations at once, and which mistakes cause wrong or surprising output.
What group_by does
group_by is a context, like select and with_columns. It splits the rows into groups by the key columns. It then evaluates the expressions you pass to agg once per group. The result has one row per group. It holds the key columns plus one column for each aggregation.
The following example uses the employee data from earlier chapters.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
summary = (
df.group_by("dept")
.agg(
pl.col("salary").mean().alias("avg_salary"),
pl.len().alias("headcount"),
)
.sort("dept")
)
print(summary)The output has two rows, one for eng and one for ops. The columns are dept, avg_salary and headcount.
shape: (2, 3)
┌──────┬────────────┬───────────┐
│ dept ┆ avg_salary ┆ headcount │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ u32 │
╞══════╪════════════╪═══════════╡
│ eng ┆ 110.0 ┆ 2 │
│ ops ┆ 85.0 ┆ 2 │
└──────┴────────────┴───────────┘Three details matter here.
pl.col("salary").mean()is an ordinary expression. Insideagg, it is applied to the salary values of one group at a time.pl.len()counts the rows in each group. It does not need a column name.- The
.sort("dept")call is there on purpose. See the next section.
Group order is not guaranteed
By default, Polars does not promise any order for the output groups. Running the same query twice can return the groups in different orders, because the work is done in parallel. If your code, a test, or a report depends on the order, sort the result explicitly.
There are two related options.
maintain_order=Truemakes the groups appear in the order in which each key first shows up in the input. It is slower and prevents some optimizations, so use it only when you need it..sort(...)after the aggregation orders the result by whatever columns you choose. This is usually the better choice, because the order is then visible in the code.
first_seen = df.group_by("dept", maintain_order=True).agg(pl.col("salary").sum())
print(first_seen)Many aggregations in one pass
Every expression in agg is evaluated independently, and Polars runs them in parallel. You can pass as many as you need, and you can transform values before or after aggregating.
stats = (
df.group_by("dept")
.agg(
pl.col("salary").min().alias("min_salary"),
pl.col("salary").max().alias("max_salary"),
(pl.col("salary").max() - pl.col("salary").min()).alias("spread"),
pl.col("name").first().alias("first_name"),
pl.col("name").alias("all_names"),
)
.sort("dept")
)
print(stats)The last expression, pl.col("name").alias("all_names"), has no aggregation function. The result for each group is therefore a list of all the names in that group. This is legal and often useful. It also means you must be careful: a forgotten aggregation does not raise an error, it quietly produces a list column.
Common aggregation methods include sum, mean, median, min, max, std, var, count, n_unique, first and last. Two of these are easy to confuse.
| Method | What it counts |
|---|---|
| `pl.len()` | All rows in the group, including nulls |
| `pl.col("x").count()` | Only the non-null values in column `x` |
| `pl.col("x").n_unique()` | Distinct values in column `x` |
If a column contains nulls, pl.len() and pl.col("x").count() give different numbers. Choose the one that matches your question. "How many employees are in each department?" needs pl.len(). "How many employees have a recorded salary?" needs count().
Grouping by several keys or by an expression
Pass a list of column names to group by a combination of keys. Each unique combination becomes one group.
sales = pl.DataFrame(
{
"region": ["north", "north", "south", "south", "south"],
"product": ["a", "b", "a", "a", "b"],
"amount": [10, 20, 5, 15, 25],
}
)
by_two = (
sales.group_by("region", "product")
.agg(pl.col("amount").sum().alias("total"))
.sort("region", "product")
)
print(by_two)Keys can also be expressions. This lets you group by a computed value without adding a helper column first.
by_size = (
sales.group_by((pl.col("amount") >= 15).alias("large"))
.agg(pl.len().alias("rows"))
.sort("large")
)
print(by_size)Remember to give the key expression an alias. Without one, the key column takes the name of the column the expression came from, which is easy to mistake for the original column.
Filtering inside an aggregation
Often you want an aggregate over only some rows of each group. Do not filter the whole DataFrame first if you also need the unfiltered numbers. Call filter inside agg instead.
conditional = (
sales.group_by("region")
.agg(
pl.col("amount").sum().alias("total"),
pl.col("amount").filter(pl.col("product") == "a").sum().alias("total_a"),
)
.sort("region")
)
print(conditional)The inner filter applies only to that one expression, within each group. The total expression still sees every row. If a group has no matching rows, the sum of an empty set is 0, while mean or max of an empty set is null.
Aggregating versus keeping every row
group_by collapses rows. Sometimes you want the group statistic next to each original row instead, for example to compare each salary with its department average. That is the job of window expressions with over, covered in the next chapter. The rule of thumb is:
- If the output should have one row per group, use
group_byandagg. - If the output should keep every input row, add the group value with
over.
Common errors
- Relying on group order. Output order can change between runs. Add
.sort(...)ormaintain_order=True. - Forgetting to aggregate. An expression in
aggwithout a reducing method returns a list per group. If you see alist[...]dtype in the schema where you expected a number, check for a missing.sum(),.mean()or similar. - Using
countwhen you meanlen.countskips nulls, so the numbers can be lower than the row count. - Duplicate output names. Two expressions on the same column without
aliasproduce the same name, and Polars raises aDuplicateError. Give each result a distinct alias. - Expecting a mean of an integer column to be an integer.
meanreturns a float. Sums of integers stay integers. - Filtering after the fact. To keep only groups with enough rows, aggregate first and then call
filteron the result, as in the next example.
big_groups = (
sales.group_by("region")
.agg(pl.len().alias("rows"))
.filter(pl.col("rows") >= 3)
)
print(big_groups)This is the Polars equivalent of SQL's HAVING. Because group_by returns an ordinary DataFrame, you can continue the chain with any context.
Exercise
A DataFrame orders has columns customer (str), status (str) and total (int). Write a query that returns, for each customer, the number of orders, the sum of total only for orders whose status is "paid", and the result sorted by customer. Give the output columns the names orders, paid_total.
Show answer
orders.groupby("customer").agg(pl.len().alias("orders"), pl.col("total").filter(pl.col("status") == "paid").sum().alias("paidtotal")).sort("customer"). The pl.len() expression counts every row in each group. The filter inside agg limits only the sum to paid orders. The final sort makes the row order deterministic.
Exercise
You run df.group_by("dept").agg(pl.col("name")) and the result has a column of dtype list[str]. Why did that happen, and how would you get the number of names per group instead?
Show answer
The expression pl.col("name") has no reducing method, so each group returns all of its values as a list. To get the count per group, use pl.col("name").count() (non-null names only) or pl.len() (all rows), each with an alias.