如何使用 Polars 按值列表过滤 df?

2024-04-12

我有来自 csv 的 Polars df ,我尝试按值列表过滤它:

list = [1, 2, 4, 6, 48]

df = (
    pl.read_csv("bm.dat", sep=';', new_columns=["cid1", "cid2", "cid3"])
    .lazy()
    .filter((pl.col("cid1") in list) & (pl.col("cid2") in list))
    .collect()
)

我收到一个错误:

ValueError:由于 Expr 是惰性的,因此 Expr 的真实性是不明确的。提示:使用“&”或“|”将 Expr 链接在一起,而不是和/或。

但当我评论的时候#.lazy() and #.collect(),我再次收到此错误。

我只尝试了一个过滤器.filter(pl.col("cid1") in list,并再次收到错误。

如何使用 Polars 按值列表过滤 df?


您的错误与使用有关in操作员。在 Polars 中,您想要使用is_in表达。

例如:

df = pl.DataFrame(
    {
        "cid1": [1, 2, 3],
        "cid2": [4, 5, 6],
        "cid3": [7, 8, 9],
    }
)


list = [1, 2, 4, 6, 48]
(
    df.lazy()
    .filter((pl.col("cid1").is_in(list)) & (pl.col("cid2").is_in(list)))
    .collect()
)
shape: (1, 3)
┌──────┬──────┬──────┐
│ cid1 ┆ cid2 ┆ cid3 │
│ ---  ┆ ---  ┆ ---  │
│ i64  ┆ i64  ┆ i64  │
╞══════╪══════╪══════╡
│ 1    ┆ 4    ┆ 7    │
└──────┴──────┴──────┘

但如果我们尝试使用in相反,我们再次得到错误。

(
    df.lazy()
    .filter((pl.col("cid1") in list) & (pl.col("cid2") in list))
    .collect()
)
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "/home/corey/.virtualenvs/StackOverflow/lib/python3.10/site-packages/polars/internals/expr/expr.py", line 155, in __bool__
    raise ValueError(
ValueError: Since Expr are lazy, the truthiness of an Expr is ambiguous. Hint: use '&' or '|' to chain Expr together, not and/or.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Polars 按值列表过滤 df? 的相关文章

随机推荐