narwhals.GroupBy
agg
agg(
*aggs: Expr | Iterable[Expr], **named_aggs: Expr
) -> DataFrameT
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 |
---|---|
DataFrameT
|
A new Dataframe. |
Examples:
Group by one column or by multiple columns and call agg
to compute
the grouped sum of another column.
>>> import pandas as pd
>>> import narwhals as nw
>>> df_native = pd.DataFrame(
... {
... "a": ["a", "b", "a", "b", "c"],
... "b": [1, 2, 1, 3, 3],
... "c": [5, 4, 3, 2, 1],
... }
... )
>>> df = nw.from_native(df_native)
>>>
>>> df.group_by("a").agg(nw.col("b").sum()).sort("a")
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| a b |
| 0 a 2 |
| 1 b 5 |
| 2 c 3 |
└──────────────────┘
>>>
>>> df.group_by("a", "b").agg(nw.col("c").sum()).sort("a", "b").to_native()
a b c
0 a 1 8
1 b 2 4
2 b 3 2
3 c 3 1