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

如何在Polars中筛选包含列表任意值的字符串行?

Polars筛选包含列表中任意字符的行

给定列表 a_list = ['a', 'b', 'c'] 和如下Polars DataFrame:

import polars as pl

a_list = ['a', 'b', 'c']

df = pl.DataFrame({
    'col1': [
        'I am just a string', 
        'one more, but without the letters', 
        'we want, a, b, c,', 
        'Nothing here'
    ]
})

需要筛选出col1列包含列表中任意字符的行,可通过以下两种方法实现:

方法1:正则表达式匹配

利用str.contains支持正则的特性,将列表元素拼接为|分隔的正则模式,即可匹配任意一个目标字符:

result = df.filter(pl.col("col1").str.contains("|".join(a_list)))
print(result)

方法2:横向任意匹配

通过any_horizontal结合列表推导式,对列表中每个元素逐一检查是否包含,最终取任意匹配成功的行:

result = df.filter(pl.any_horizontal(pl.col("col1").str.contains(x) for x in a_list))
print(result)

两种方法的输出均符合预期:

shape: (3, 1)
┌───────────────────────────────────┐
│ col1                              │
│ ---                               │
│ str                               │
╞═══════════════════════════════════╡
│ I am just a string                │
│ one more, but without the letter… │
│ we want, a, b, c,                 │
└───────────────────────────────────┘

注:之前尝试结合.is_in(a_list)与.str.contains()失败,是因为is_in用于检查元素是否完全存在于列表中,而str.contains是检查字符串是否包含子串,二者逻辑不兼容,上述两种方法才是正确的实现思路。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:05:16