繁体   English   中英

检查 Python Polars DataFrame 行值是否存在于定义的列表中

[英]Check if Python Polars DataFrame row value exists within a defined list

我真的是 Polars (v0.15.8) 的新手……所以我真的不知道自己在做什么。

我有一个 Dataframe,我想检查列中的每一行是否存在于单独定义的列表中。

例如,这是我的清单:

list_animal = ['cat', 'mouse', 'dog', 'sloth', 'zebra']

这是我的 Dataframe:

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

...看起来像这样:

在此处输入图像描述

我希望 df 最终像这样:

在此处输入图像描述

我正在努力通过一些示例和 Polars 文档。 我找到了两个选择:

  1. 使用 pl.when function:
df = (df.with_column(
     pl.when(
         (pl.col("thing") in list_animal)
     )
     .then(True)
     .otherwise(False)
     .alias("isAnimal2")
))

但是,我收到一个错误:

ValueError: Since Expr are lazy, the truthiness of an Expr is ambiguous. Hint: use '&' or '|' to chain Expr together, not and/or.

要么,

  1. 使用此处的文档,我尝试按照示例对列表的元素应用表达式。 我无法让它工作,但我试过这个:
chk_if_true = pl.element() in list_animal

df.with_column(
    pl.col("thing").arr.eval(chk_if_true, parallel=True).alias("isAnimal2")

)

...这给了我这个错误:

SchemaError: Series of dtype: Utf8 != List

我将不胜感激任何建议; 谢谢!

你正在寻找.is_in()

>>> df.with_column(pl.col("thing").is_in(list_animal).alias("isAnimal2"))
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     │
└───────┴──────────┴───────────┘

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM