Grouped summaries
Summarize numeric measures such as totals, averages, or counts separately for each category.
Polars · Function
Compute one or more aggregations for every group in a DataFrame group-by operation. Positional expressions and named keyword aggregations can be combined.
GroupBy.agg computes one or more expressions independently for every group created by group_by. Positional expressions determine aggregation columns from their expressions, while keyword expressions additionally rename their results to the supplied keyword; string positional inputs are interpreted as column names.
GroupBy.agg(*aggs: IntoExpr | Iterable[IntoExpr], **named_aggs: IntoExpr) → DataFrame| Name | Type | Description |
|---|---|---|
aggs | IntoExpr | Iterable[IntoExpr] | Aggregations to compute for each group of the group by operation, specified as positional arguments. Accepts expression input; strings are parsed as column names. |
named_aggs | IntoExpr | Additional aggregations, specified as keyword arguments. The resulting columns will be renamed to the keyword used. |
DataFrame
import polars as pl
df = pl.DataFrame({"team": ["A", "A", "B"], "score": [3, 5, 4]})
result = df.group_by("team").agg(
pl.col("score").sum().alias("total_score"),
average=pl.col("score").mean(),
)
print(result)Groups rows by team and computes both a positional sum expression and a named mean expression.
Summarize numeric measures such as totals, averages, or counts separately for each category.
Produce several result columns while assigning stable, readable names through keyword aggregations.
GroupBy.agg computes aggregations for every group produced by a group-by operation. It accepts expressions as positional arguments, and keyword arguments provide additional aggregations whose output names come from the keywords.
Follow-up: How can an aggregation column be named explicitly? Use a keyword aggregation, such as total=pl.col("amount").sum(), or alias the expression.
Positional aggregations are supplied through the aggs parameter, which accepts an expression or an iterable of expressions. Strings in that position are interpreted as column names.
Follow-up: What happens when several expressions are provided? Each expression contributes an aggregation result for every group.
Keyword aggregations are supplied through named_aggs. The resulting columns are renamed to the corresponding keyword, which makes the output schema explicit.
Follow-up: Why use a keyword aggregation instead of only an alias? It directly associates the desired output name with the expression at the call site.
polars.DataFrame.group_bypolars.lazyframe.group_by.LazyGroupBy.agg