You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何筛选Polars DataFrame中列表列包含指定值的行

筛选Polars DataFrame中列表列包含指定值的行

针对你的需求,这里提供两种简洁的实现方式:

方法一:使用list.contains()(推荐)

这是Polars专门为列表列提供的方法,直接检查列表是否包含目标值,代码简洁且高效:

import polars as pl

df = pl.DataFrame(
{
    "foo": [[1, 3, 5], [2, 6, 7], [3, 8, 10]],
    "bar": [6, 7, 8],
    "ham": ["a", "b", "c"],
})

# 筛选foo列包含值3的行
filtered_df = df.filter(pl.col("foo").list.contains(3))
print(filtered_df)

执行后输出:

shape: (2, 3)
┌────────────┬─────┬─────┐
│ foo        ┆ bar ┆ ham │
│ ---        ┆ --- ┆ --- │
│ list[i64]  ┆ i64 ┆ str │
╞════════════╪═════╪═════╡
│ [1, 3, 5]  ┆ 6   ┆ a   │
│ [3, 8, 10] ┆ 8   ┆ c   │
└────────────┴─────┴─────┘

方法二:使用list.eval()结合list.any()

如果需要更灵活的元素判断逻辑,可以用这种方式:先对列表每个元素做比较,再判断是否存在符合条件的元素:

filtered_df = df.filter(pl.col("foo").list.eval(pl.element() == 3).list.any())

说明

  • list.contains(3):直接检查每个列表是否包含数值3,返回布尔序列,filter()方法根据这个序列保留对应行。
  • list.eval(pl.element() ==3):对每个列表中的元素逐一判断是否等于3,生成布尔值组成的列表;list.any()则判断这个布尔列表中是否存在True,即原列表是否包含目标值。

内容的提问来源于stack exchange,提问作者andrdpedro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 06:02:36