Skip to content

narwhals.LazyGroupBy

agg(*aggs: Expr | Iterable[Expr], **named_aggs: Expr) -> LazyFrameT

Compute aggregations for each group of a group by operation.

Parameters:

Name Type Description Default
aggs Expr | Iterable[Expr]

Aggregations to compute for each group of the group by operation, specified as positional arguments.

()
named_aggs Expr

Additional aggregations, specified as keyword arguments.

{}

Returns:

Type Description
LazyFrameT

A new LazyFrame.

Examples:

Group by one column or by multiple columns and call agg to compute the grouped sum of another column.

>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoFrameT
>>> lf_native = pl.LazyFrame(
...     {
...         "a": ["a", "b", "a", "b", "c"],
...         "b": [1, 2, 1, 3, 3],
...         "c": [5, 4, 3, 2, 1],
...     }
... )
>>> lf = nw.from_native(lf_native)
>>>
>>> nw.to_native(lf.group_by("a").agg(nw.col("b").sum()).sort("a")).collect()
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ a   ┆ 2   │
│ b   ┆ 5   │
│ c   ┆ 3   │
└─────┴─────┘
>>>
>>> lf.group_by("a", "b").agg(nw.sum("c")).sort("a", "b").collect()
┌───────────────────┐
|Narwhals DataFrame |
|-------------------|
|shape: (4, 3)      |
|┌─────┬─────┬─────┐|
|│ a   ┆ b   ┆ c   │|
|│ --- ┆ --- ┆ --- │|
|│ str ┆ i64 ┆ i64 │|
|╞═════╪═════╪═════╡|
|│ a   ┆ 1   ┆ 8   │|
|│ b   ┆ 2   ┆ 4   │|
|│ b   ┆ 3   ┆ 2   │|
|│ c   ┆ 3   ┆ 1   │|
|└─────┴─────┴─────┘|
└───────────────────┘