Grouped aggregation
Summarize measures by category, customer, or other keys.
Polars · Function
Starts a DataFrame grouping operation and returns a GroupBy object. Grouping keys may be columns or expressions, with optional preservation of group order.
Calling group_by starts a grouping operation on a DataFrame. Supply one or more column names or expressions, optionally preserve group order, then use the returned GroupBy object to aggregate, inspect, or iterate through the groups.
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 expression input. Strings are parsed as column names. |
maintain_order | bool = False | Whether to keep group order consistent with the input data. The default is false. |
named_by | IntoExpr | Additional grouping columns supplied as keyword arguments; each column is renamed to its keyword. |
A GroupBy object that can be used to perform aggregations.
by to specify one or more grouping keys.named_by.named_by becomes the output name for that grouping column.maintain_order=True preserves the order in which groups appear, but can make execution slower.maintain_order=True prevents execution with the streaming engine.import polars as pl
df = pl.DataFrame({"team": ["A", "A", "B"], "points": [10, 15, 7]})
result = df.group_by("team").agg(pl.col("points").sum())
print(result)Groups rows by team and computes the sum of points for each group.
Summarize measures by category, customer, or other keys.
Partition rows for per-group inspection or iteration.
Create derived grouping buckets with Polars expressions.
DataFrame.group_by return, and how is it used?DataFrame.group_by starts a grouping operation and returns a GroupBy object. Aggregations are then applied through methods such as agg, sum, or len.
Follow-up: How would you preserve input group order? Set maintain_order=True, accepting the performance and streaming limitations.
group_by accept?The by argument accepts a column name, multiple grouping columns, or expressions. Strings are interpreted as column names, while expressions can derive grouping keys.
Follow-up: How can grouped output use a renamed key? Pass an expression as a keyword argument through named_by.
maintain_order?maintain_order=True keeps the order of groups consistent with the input data. It does not change row order within each group, which is preserved regardless of this setting.
Follow-up: Why might the default be preferable? It is faster and retains compatibility with the streaming engine.
GroupByGroupBy.aggGroupBy.lenGroupBy.sumGroupBy.__iter__