我们如何将聚合函数作为参数传递给 Polars 中的自定义聚合函数?如果按列进行不同的聚合,则应该能够为所有列或字典传递单个函数。
import polars as pl
# Sample DataFrame
df = pl.DataFrame({
"category": ["A", "A", "B", "B", "B"],
"value": [1, 2, 3, 4, 5]
})
def agg_with_sum(df: pl.DataFrame | pl.LazyFrame) -> pl.DataFrame | pl.LazyFrame:
return df.group_by("category").agg(pl.col("*").sum())
# Custom function to perform aggregation
def agg_with_expr(df: pl.DataFrame | pl.LazyFrame,
agg_expr: pl.Expr | dict[str, pl.Expr]) -> pl.DataFrame | pl.LazyFrame:
if isinstance(agg_expr, dict):
return df.group_by("category").agg([pl.col(col).aggexpr() for col, aggexpr in agg_expr.items()])
return df.group_by("category").agg(pl.col("*").agg_expr())
# Trying to pass a Polars expression for sum aggregation
print(agg_with_sum(df))
# ┌──────────┬───────┐
# │ category ┆ value │
# │ --- ┆ --- │
# │ str ┆ i64 │
# ╞══════════╪═══════╡
# │ A ┆ 3 │
# │ B ┆ 12 │
# └──────────┴───────┘
# Trying to pass a custom Polars expression
print(agg_with_expr(df, pl.sum))
# AttributeError: 'Expr' object has no attribute 'agg_expr'
print(agg_with_expr(df, {'value': pl.sum}))
# AttributeError: 'Expr' object has no attribute 'aggexpr'