Grouped summaries
Summarize numeric columns by category, customer, or other grouping keys.
Polars · Module
Computes one or more expression-based aggregations for every group in a GroupBy object. Positional and keyword aggregations are supported, with keyword names becoming output column names.
GroupBy.agg evaluates one or more expressions for every group created by group_by. Positional expressions retain their expression-derived names, while keyword expressions create output columns using the supplied keyword names.
GroupBy.agg(**aggs: IntoExpr | Iterable[IntoExpr]*, ***named_aggs: IntoExpr*) → DataFrame| Name | Type | Description |
|---|---|---|
aggs | IntoExpr | Iterable[IntoExpr] | Aggregations to compute for each group, specified as positional arguments. Accepts expression input; strings are parsed as column names. |
named_aggs | IntoExpr | Additional aggregations specified as keyword arguments; output columns use the corresponding keyword names. |
DataFrame
import polars as pl
df = pl.DataFrame({
"group": ["a", "a", "b"],
"value": [1, 2, 3],
})
result = df.group_by("group").agg(
total=pl.col("value").sum(),
average=pl.col("value").mean(),
)
print(result.sort("group"))Groups rows by group and produces named sum and mean columns.
Summarize numeric columns by category, customer, or other grouping keys.
Return the values associated with each group as list-valued columns.
Produce several clearly named metrics in one grouped operation.
GroupBy.agg do and how are its arguments named?GroupBy.agg computes aggregations independently for every group. It accepts expressions positionally, and it can also accept keyword expressions whose keywords become the output column names.
Follow-up: How can several aggregations be supplied together? Pass multiple positional expressions or an iterable such as a list of expressions.
A column expression without a reducing operation collects the values belonging to each group, while an expression such as pl.col("b").sum() reduces each group to one value. The resulting DataFrame includes the grouping columns and aggregation outputs.
Follow-up: How would you create a custom output name? Use a keyword aggregation or apply .alias(...) to the expression.
Keyword aggregations are additional expressions supplied with names such as total=pl.col("b").sum(). The resulting columns are renamed to those keywords, which is useful when several outputs derive from the same input column.
Follow-up: What is the equivalent positional form? Use the expression positionally and rename it with .alias("total") when needed.
polars.DataFrame.group_bypolars.LazyFrame.group_bypolars.dataframe.group_by.GroupBy