You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polars中Pandas groupby transform等价实现及组内累加和方法问询

Polars 实现 Pandas groupby.transform 功能的最优方案

1. 组内归一化的最优实现

你当前用join的方式虽能达成需求,但并非最优解。Polars提供的窗口函数over,可以直接实现类似Pandas transform的广播逻辑,无需额外的join操作,代码更简洁且性能更优。

对应组内归一化的Polars代码:

df = df.with_columns(
    (pl.col('VOL') / pl.col('VOL').sum().over(groupcols)).alias('VOLNORM')
)

这个写法通过over(groupcols)指定分组范围,计算每组总和后与原列做除法,自动将结果广播到组内每一行,省去了join及临时列的创建、删除步骤。

2. 组内累加和的实现

完全可以用Polars的窗口函数实现等价于Pandas groupby.transform('cumsum')的功能,同样借助over指定分组,结合cumsum()方法即可:

对应组内累加和的Polars代码:

df = df.with_columns(
    pl.col(col).cumsum().over(groupcols).alias('cummulativesum')
)

这里cumsum().over(groupcols)会在每个分组内独立计算累加和,结果与Pandas的transform实现完全一致。

完整示例

假设groupcols为['category'],col为'VOL',完整Polars代码如下:

import polars as pl

# 构造示例数据
df = pl.DataFrame({
    'category': ['A', 'A', 'B', 'B', 'B'],
    'VOL': [10, 20, 5, 15, 20]
})

# 组内归一化
df = df.with_columns(
    (pl.col('VOL') / pl.col('VOL').sum().over('category')).alias('VOLNORM')
)

# 组内累加和
df = df.with_columns(
    pl.col('VOL').cumsum().over('category').alias('cummulativesum')
)

print(df)

输出结果:

shape: (5, 4)
┌──────────┬─────┬──────────┬────────────────┐
│ category ┆ VOL ┆ VOLNORM  ┆ cummulativesum │
│ ---      ┆ --- ┆ ---      ┆ ---            │
│ str      ┆ i64 ┆ f64      ┆ i64            │
╞══════════╪═════╪══════════╪════════════════╡
│ A        ┆ 10  ┆ 0.333333 ┆ 10             │
│ A        ┆ 20  ┆ 0.666667 ┆ 30             │
│ B        ┆ 5   ┆ 0.125    ┆ 5              │
│ B        ┆ 15  ┆ 0.375    ┆ 20             │
│ B        ┆ 20  ┆ 0.5      ┆ 40             │
└──────────┴─────┴──────────┴────────────────┘

内容的提问来源于stack exchange,提问作者Mitchell Baskerville

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:15:43