Polars 0.20存在0.19无的Bug,有无简便规避方案?
Polars 0.20.19分组聚合断言错误的临时解决方法
问题说明
Polars 0.20.19版本存在回归Bug:在group_by.agg中使用分组内分位数、极值作为过滤条件时,会抛出assertion failed: lhs.len() == rhs.len()错误,0.19版本无此问题。示例触发代码:
df.group_by("SomeDate") .agg( pl.col(col) .filter( pl.col(col).is_between( pl.quantile(col, 0.005), pl.quantile(col, 0.995) ) ) .mean() )
- 替换分位数为
pl.min(col)/pl.max(col)时问题复现 - 使用固定数值(如
pl.col(col).is_between(10, 90))则可正常运行
临时简便解决方案
方案1:用窗口函数提前计算分组统计量
无需拆分关联操作,直接在原DataFrame中通过窗口函数生成各组的分位数/极值列,再完成过滤聚合,仅需遍历一次目标列:
target_cols = ["col1", "col2", ...] # 替换为你需要处理的列列表 # 先添加分组统计量列 df_with_stats = df.with_columns( [ pl.quantile(col, 0.005).over("SomeDate").alias(f"{col}_q005"), pl.quantile(col, 0.995).over("SomeDate").alias(f"{col}_q995") ] for col in target_cols ) # 过滤后执行分组聚合 result = df_with_stats.group_by("SomeDate").agg( [ pl.col(col) .filter(pl.col(col).is_between(pl.col(f"{col}_q005"), pl.col(f"{col}_q995"))) .mean().alias(col) ] for col in target_cols )
如果是用min/max做过滤,只需把pl.quantile替换为pl.min/pl.max即可。
方案2:临时回退到0.19.x版本
若不想修改代码,可直接降级Polars版本:
pip install polars==0.19.19
补充建议
该问题属于版本回归,建议到Polars官方仓库提交Issue跟进修复进度。
内容的提问来源于stack exchange,提问作者wordsforthewise
相关产品推荐
相关产品推荐

