根据 Polars 中另一个列表的值过滤列表

问题描述 投票:0回答:1

假设我有以下数据框:

df = pl.DataFrame({
    'values': [[0, 1], [9, 8]],
    'qc_flags': [["", "X"], ["T", ""]]
})

我只想在相应的 qc_flag 等于“”时保留我的值。

有人知道正确的方法吗?

我尝试过这样的事情:

filtered = df.with_columns(
    pl.col("values").list.eval(
        pl.element().filter(
            pl.col("qc_flags").list.eval(
                pl.element() == ""
            )
        )
    )
)

我希望得到“值”:[[0],[8]],但最终我得到了这个错误:

ComputeError: named columns are not allowed in `list.eval`; consider using `element` or `col("")`
python python-polars
1个回答
0
投票

您可以添加一个临时列来跟踪列表中的哪个元素来自,将列表分解为适当的系列,进行过滤,然后再次按该列分组:

(df
    .lazy()
    .with_row_index()
    .group_by("index")
    .agg(
        pl.col.values.explode().filter(pl.col.qc_flags.explode() == "")
    )
    .drop("index")
    .collect())

输出:

shape: (2, 1)
┌───────────┐
│ values    │
│ ---       │
│ list[i64] │
╞═══════════╡
│ [0]       │
│ [8]       │
└───────────┘
© www.soinside.com 2019 - 2024. All rights reserved.