Sub topic 2
Summarizing groups with group_by and agg
This chapter assumes you know basic Python, can create a Polars DataFrame, and can pick columns with pl.col. It also assumes you know that Polars runs expressions inside a context such as select or with_columns. Here the context is group_by(...).agg(...).
The working model
group_by splits a DataFrame into groups of rows that share the same key values. agg evaluates one or more expressions on each group and collects the results into a new DataFrame.
The result has these properties:
- It has one row per distinct key combination.
- The key columns come first, followed by one column per aggregation expression.
- The row count is usually smaller than the input. Compare this with
over, which keeps every row. A later chapter covers it.
A first aggregation
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 3| region | total | rows |
|---|---|---|
| east | 30 | 2 |
| west | 45 | 3 |
pl.col("sales").sum() is an expression. Inside agg, Polars evaluates it once per group. pl.len() returns the number of rows in each group.
The final .sort("region") matters. By default, group_by does not promise any particular order for the output rows, and the order can change between runs. Sort the result whenever order matters, such as in tests or reports. The next chapters cover maintain_order.
Naming the output columns
An aggregation keeps the name of the column it reads from. This causes a problem when you aggregate the same column twice:
# Raises an error: both outputs would be named "sales".
df.group_by("region").agg(
pl.col("sales").sum(),
pl.col("sales").mean(),
)Polars rejects this because the result would contain two columns called sales. You can fix it in two ways. The first is .alias(...), as above. The second is keyword arguments, where the keyword becomes the column name:
out = df.group_by("region").agg(
total=pl.col("sales").sum(),
biggest=pl.col("sales").max(),
average=pl.col("sales").mean(),
).sort("region")
print(out) # east: 30, 20, 15.0; west: 45, 25, 15.0Keyword arguments and positional expressions can be mixed in one agg call. Put the positional ones first, as Python requires.
Aggregating many columns at once
One expression can target several columns. You then get one output column per input column:
orders = pl.DataFrame({
"region": ["east", "east", "west", "west"],
"sales": [10, 20, 5, 15],
"units": [1, 2, 1, 3],
})
out = orders.group_by("region").agg(
pl.col("sales", "units").sum().name.suffix("_sum")
).sort("region")
print(out) # columns: region, sales_sum, units_sumname.suffix("_sum") renames every output column. Without it the columns would be called sales and units. That is fine here, because the names do not collide.
pl.all() inside agg selects every column except the grouping keys. It is convenient on all-numeric data, but it fails if any remaining column cannot be summed, such as a string column.
Grouping by several keys
Pass more than one key and each distinct combination becomes a group:
out = (
df.group_by("region", "product")
.agg(pl.col("sales").sum().alias("total"))
.sort("region", "product")
)
print(out) # east/a 10, east/b 20, west/a 5, west/b 40Keys can also be expressions. Give a computed key an alias so the output column has a clear name:
out = (
df.group_by(pl.col("product").str.to_uppercase().alias("PRODUCT"))
.agg(pl.col("sales").sum())
.sort("PRODUCT")
)
print(out) # A: 15, B: 60Which expressions work inside agg
Most useful agg expressions reduce a group to one value:
sum,mean,median,min,max,std,varfirst,lastn_uniquelen,count, andnull_count
You can combine reductions with ordinary arithmetic, because the arithmetic runs on the reduced values:
out = df.group_by("region").agg(
(pl.col("sales").max() - pl.col("sales").min()).alias("spread"),
pl.col("product").n_unique().alias("distinct_products"),
).sort("region")
print(out) # east: spread 10, 2 products; west: spread 20, 2 productsExpressions that do not reduce
An expression that returns several values per group is also allowed. Polars stores the values in a list cell:
out = df.group_by("region").agg(pl.col("product")).sort("region")
print(out) # east: ["a", "b"]; west: ["a", "b", "b"]Rows keep their original relative order inside each list. This is useful for inspecting groups, and the explode method turns a list column back into rows. If you expected a scalar and see a list[...] column, you forgot to apply a reduction.
Nulls and counting
Aggregations treat nulls in the value column as missing data. Null keys are not discarded. All rows with a null key form one group of their own.
nulls = pl.DataFrame({
"k": ["x", None, "x", None],
"v": [1, 2, None, 4],
})
out = nulls.group_by("k").agg(
pl.col("v").sum().alias("sum_v"),
pl.col("v").count().alias("count_v"),
pl.len().alias("len"),
).sort("k")
print(out)| k | sum_v | count_v | len |
|---|---|---|---|
| null | 6 | 2 | 2 |
| x | 1 | 1 | 2 |
sort places the null group first by default. The two counting expressions differ:
pl.len()counts rows, including rows where the value is null.pl.col("v").count()counts only the non-null values.
For "how many rows per group", use pl.len().
Common errors
- Duplicate output names. Aggregating one column twice without aliases raises an error. Alias each expression or use keyword arguments.
- Relying on output order. Rows can come back in a different order from run to run. Sort the result, or use
maintain_order=Truewhere the order of first appearance is enough. - Forgetting the reduction. A bare
pl.col("x")inaggproduces a list column. - Expecting the original row count.
group_byshrinks the table. If you need a group value attached to every original row, useover. - Using a key in
pl.all().pl.all()skips the grouping keys insideagg. To summarize a key column, reference it explicitly. You can usepl.col("region").first(), although it is rarely meaningful.
Exercise
Using the df from this chapter (columns region, product, sales), write a group_by that returns, for each product, the number of rows as n, the total sales as total, and the highest single sale as best, sorted by product. What are the values for product "b"?
Show answer
Code: df.group_by("product").agg(n=pl.len(), total=pl.col("sales").sum(), best=pl.col("sales").max()).sort("product"). Product "b" appears in rows with sales 20, 15, and 25, so n is 3, total is 60, and best is 25.
Exercise
A DataFrame has a column k with values ["x", None, "x", None] and a column v with values [1, 2, None, 4]. For the null-key group, what do pl.len() and pl.col("v").count() return, and why does the result still contain a null-key row?
Show answer
Both return 2, because both null-key rows have non-null values (2 and 4). The null-key row still appears because group_by treats null as a key value and puts all rows with a null key into one group. For group "x", the two expressions differ: len is 2 and count is 1, because one v value is null.