Grouped aggregation
Summarize measures by category, customer, or other keys.
Polars · Module
Starts a group-by operation over columns or expressions and returns a GroupBy object for per-group aggregation. Group order can optionally follow input order with maintain_order=True.
Call group_by with one or more grouping columns or expressions to obtain a GroupBy object. Use that object’s aggregation methods, such as agg, to calculate results per group; optionally enable maintain_order when group order must follow the input.
DataFrame.group_by(by: IntoExpr | Iterable[IntoExpr], maintain_order: bool = False, **named_by: IntoExpr) → GroupBy| Name | Type | Description |
|---|---|---|
by | IntoExpr | Iterable[IntoExpr] | Column(s) to group by; accepts expressions, and strings are interpreted as column names. |
maintain_order | bool = False | Whether group order should follow input order; enabled ordering may be slower and disables streaming. |
named_by | IntoExpr | Additional grouping columns supplied as keyword arguments; each output grouping column uses its keyword name. |
GroupBy object used to perform aggregations.
by to specify the columns or expressions that define group membership.maintain_order=True can reduce performance compared with the default behavior.maintain_order=True prevents execution with the streaming engine.import polars as pl
df = pl.DataFrame({"team": ["A", "A", "B"], "points": [10, 20, 7]})
result = df.group_by("team").agg(
pl.col("points").sum().alias("total_points")
)
print(result.sort("team"))Groups rows by team and computes the total points for each group.
Summarize measures by category, customer, or other keys.
Build groups from calculated expressions instead of only existing columns.
Inspect or process rows belonging to each group.
Preserve the order in which groups first appear in the input.
DataFrame.group_by return and how is it used?DataFrame.group_by starts a grouping operation and returns a GroupBy object. Aggregations are then performed through methods such as agg.
Follow-up: How would you preserve input group order? Use maintain_order=True, accepting its performance and streaming limitations.
group_by accept?The by argument accepts a column name, multiple columns, or expressions. A string is interpreted as a column name, while expressions allow computed grouping keys.
Follow-up: How can multiple grouping keys be supplied? Pass an iterable of expressions or column names, or use named keyword arguments for additional renamed grouping columns.
maintain_order be enabled?By default, the ordering of groups is not guaranteed to match the input order. Setting maintain_order=True makes group order consistent with the input data.
Follow-up: Does this option reorder rows inside each group? No; row order within every group remains preserved regardless of the setting.
polars.dataframe.group_by.GroupByGroupBy.aggGroupBy.lenGroupBy.sumDataFrame.group_by_dynamic