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

如何在Polars的.when条件判断中使用与/或布尔逻辑?

问题解决:Polars中组合逻辑条件生成新列

错误原因拆解

  • 使用and报错:Polars的表达式(Expr)是惰性求值的向量对象,Python原生的and只能处理单个布尔值,无法识别这种批量逻辑判断,因此必须使用Polars支持的向量级逻辑运算符。
  • 使用&报错:运算符优先级踩坑,&的优先级高于==,导致代码实际执行的是"?" & pl.col("src").is_not_null()——这是在对字符串和布尔列做按位与操作,完全不符合逻辑,自然报错。

正确实现代码

给两个条件分别加括号,确保先各自计算出布尔结果,再用&做向量式的逻辑与:

import polars as pl
df = pl.from_dict(
    dict(tgt=["a","?","?"],src=["!a","b",None])
)

df_result = df.with_columns(
    pl.when((pl.col("tgt") == "?") & (pl.col("src").is_not_null()))
    .then(pl.col("src"))
    .otherwise(pl.col("tgt"))
    .alias("newtgt")
)

print(df_result)

预期输出

shape: (3, 3)
┌─────┬──────┬────────┐
│ tgt ┆ src  ┆ newtgt │
│ --- ┆ ---  ┆ ---    │
│ str ┆ str  ┆ str    │
╞═════╪══════╪════════╡
│ a   ┆ !a   ┆ a      │
│ ?   ┆ b    ┆ b      │
│ ?   ┆ null ┆ ?      │
└─────┴──────┴────────┘

更清晰的写法(可选)

用pl.all_horizontal()直接组合多个条件,避免优先级问题,代码可读性更强:

df_result = df.with_columns(
    pl.when(pl.all_horizontal(pl.col("tgt") == "?", pl.col("src").is_not_null()))
    .then(pl.col("src"))
    .otherwise(pl.col("tgt"))
    .alias("newtgt")
)

内容的提问来源于stack exchange,提问作者JL Peyret

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:55:31