如何检查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 │ └────────┴─────────┴───────────┘
为什么之前的方法报错?
- 第一种方法里的
pl.col("thing") in list_animal是Python层面的操作,Polars表达式对象无法被in直接判断,因此触发歧义错误。 - 第二种方法误用了
list.eval——这个方法是用来处理列表类型的列,而你的thing列是字符串类型,同时pl.element() in list_animal同样犯了用Python原生in处理表达式的错误。
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

