polars.map_groups#

polars.map_groups(
exprs: Sequence[str | Expr],
function: Callable[[Sequence[Series]], Series | Any],
return_dtype: PolarsDataType | None = None,
*,
returns_scalar: bool = True,
) Expr[source]#

在GroupBy上下文中应用自定义/用户定义的函数(UDF)。

警告

此方法比原生表达式API慢得多。 只有在无法以其他方式实现逻辑时才使用它。

Parameters:
exprs

表示输入Series到函数的表达式。

function

应用于输入的函数;应为类型 Callable[[Series], Series]。

return_dtype

输出Series的数据类型。

returns_scalar

如果函数返回单个标量作为输出。

Returns:
Expr

表达式具有由return_dtype给出的数据类型。

示例

>>> df = pl.DataFrame(
...     {
...         "group": [1, 1, 2],
...         "a": [1, 3, 3],
...         "b": [5, 6, 7],
...     }
... )
>>> df
shape: (3, 3)
┌───────┬─────┬─────┐
│ group ┆ a   ┆ b   │
│ ---   ┆ --- ┆ --- │
│ i64   ┆ i64 ┆ i64 │
╞═══════╪═════╪═════╡
│ 1     ┆ 1   ┆ 5   │
│ 1     ┆ 3   ┆ 6   │
│ 2     ┆ 3   ┆ 7   │
└───────┴─────┴─────┘
>>> (
...     df.group_by("group").agg(
...         pl.map_groups(
...             exprs=["a", "b"],
...             function=lambda list_of_series: list_of_series[0]
...             / list_of_series[0].sum()
...             + list_of_series[1],
...             return_dtype=pl.Float64,
...         ).alias("my_custom_aggregation")
...     )
... ).sort("group")
shape: (2, 2)
┌───────┬───────────────────────┐
│ group ┆ my_custom_aggregation │
│ ---   ┆ ---                   │
│ i64   ┆ list[f64]             │
╞═══════╪═══════════════════════╡
│ 1     ┆ [5.25, 6.75]          │
│ 2     ┆ [8.0]                 │
└───────┴───────────────────────┘

1的输出可以理解如下:

  • 1 包含系列 'a': [1, 3]'b': [5, 6]

  • 将函数应用于这些Series列表,可以得到输出 [1 / 4 + 5, 3 / 4 + 6],即 [5.25, 6.75]