【发布时间】:2022-12-31 13:22:18
【问题描述】:
我真的是 Polars (v0.15.8) 的新手……所以我真的不知道自己在做什么。
我有一个数据框,我想检查列中的每一行是否存在于单独定义的列表中。
例如,这是我的清单:
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]),
])
...看起来像这样:
我希望 df 最终像这样:
我正在努力通过一些示例和 Polars 文档。我找到了两个选择:
- 使用 pl.when 函数:
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.要么,
- 使用文档here,我尝试按照示例对列表的元素应用表达式。我无法让它工作,但我试过这个:
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我将不胜感激任何建议;谢谢!
【问题讨论】:
标签: python dataframe python-polars