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

如何检查Python Polars DataFrame行值是否存在于指定列表中

解决Polars中检查列值是否在列表中的问题

你遇到的错误是因为Python原生的in运算符无法直接用于Polars表达式——Polars的表达式是延迟计算的对象,不能直接用in来判断布尔值,这就导致了TypeError: the truth value of an Expr is ambiguous报错。

正确实现方式

Polars提供了专门的is_in()表达式方法来处理这类“值是否在列表中”的判断,直接返回布尔列,无需额外的when逻辑(当然用when也能实现,但没必要)。

方法1:直接使用is_in()(推荐)

list_animal = ['cat', 'mouse', 'dog', 'sloth', 'zebra']
df = pl.DataFrame([
    pl.Series('thing', ['cat', 'plant', 'mouse', 'dog', 'sloth', 'zebra', 'shoe']),
    pl.Series('isAnimal', [None, None, None, None, None, None, None]),
])

# 生成isAnimal2列
df = df.with_columns(
    pl.col("thing").is_in(list_animal).alias("isAnimal2")
)

方法2:结合when使用is_in()

如果一定要用when逻辑,只需要把条件替换为pl.col("thing").is_in(list_animal)即可:

df = df.with_columns(
    pl.when(pl.col("thing").is_in(list_animal))
    .then(True)
    .otherwise(False)
    .alias("isAnimal2")
)

执行结果

最终生成的DataFrame如下:

shape: (7, 3)
┌────────┬─────────┬───────────┐
│ thing  ┆ isAnimal┆ isAnimal2 │
│ ---    ┆ ---     ┆ ---       │
│ str    ┆ f64     ┆ bool      │
╞════════╪═════════╪═══════════╡
│ cat    ┆ null    ┆ true      │
│ plant  ┆ null    ┆ false     │
│ mouse  ┆ null    ┆ true      │
│ dog    ┆ null    ┆ true      │
│ sloth  ┆ null    ┆ true      │
│ zebra  ┆ null    ┆ true      │
│ shoe   ┆ null    ┆ false     │
└────────┴─────────┴───────────┘

为什么之前的方法报错?

  1. 第一种方法里的pl.col("thing") in list_animal是Python层面的操作,Polars表达式对象无法被in直接判断,因此触发歧义错误。
  2. 第二种方法误用了list.eval——这个方法是用来处理列表类型的列,而你的thing列是字符串类型,同时pl.element() in list_animal同样犯了用Python原生in处理表达式的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:51:28