在Polars聚合操作中使用条件表达式时如何避免警告?
Polars聚合内使用条件表达式时消除警告的方法
更新提示
聚合中的向量化规则现已正式确定,该警告不再存在。
先看示例DataFrame:
import polars as pl df = pl.DataFrame({ "group": [1, 1, 2, 2], "value": [10, None, 30, None], })
实现空值填充后聚合,有两种无警告的方式:
- 直接用
fill_null在聚合步骤中处理:
df.groupby("group").agg( pl.col("value").fill_null(20).min() )
- 先通过
with_columns做条件填充,再执行聚合:
df.with_columns( pl.when(pl.col("value").is_null()).then(pl.lit(20)).otherwise(pl.col("value")) ).groupby("group").agg( pl.col("value").min() )
但如果直接在聚合内部写条件表达式,会触发如下警告:
df.groupby("group").agg( pl.when(pl.col("value").is_null()).then(pl.lit(20)).otherwise(pl.col("value")).min() ) # 警告信息: # The predicate 'col("value").is_null()' in 'when->then->otherwise' is not a valid aggregation # and might produce a different number of rows than the groupby operation would. # This behavior is experimental and may be subject to change
实际上这个警告在此场景下并不合理——该条件表达式和fill_null效果完全等价,但后者不会触发警告。
消除警告的可行方法
- 优先用
fill_null替代条件表达式:这是最贴合Polars设计的方案,代码简洁,还能享受内置优化,完全不会触发警告。 - 用
map包裹条件表达式:通过map显式标记操作是逐元素的组内转换,让Polars识别其合法性:
df.groupby("group").agg( pl.col("value").map(lambda s: pl.when(s.is_null()).then(20).otherwise(s)).min() )
- 升级Polars到最新版本:根据更新提示,聚合的向量化规则已正式确定,新版本中该警告已被移除,升级后问题自然解决。
- 临时关闭实验性警告(不推荐):若确认场景安全,可通过配置关闭所有未来相关警告,但可能错过其他重要提示:
import polars as pl pl.Config.set_future_warnings(False)
内容的提问来源于stack exchange,提问作者datenzauber.ai
相关产品推荐
相关产品推荐

