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

如何使用Polars在列中搜索多个子字符串?

如何使用Polars在列中搜索多个子字符串?

嗨,我来帮你把这段Pandas代码转换成Polars的实现,思路其实和你熟悉的Pandas逻辑很像,用正则匹配就能轻松搞定多个子串的搜索需求~

先回顾下你的需求:从DataFrame里筛选出col1列包含best或dog任意一个子串的行,对应你的Pandas代码是这样的:

import pandas as pd
df = pd.DataFrame({'col1':['a red','dog','liked to play','with his best friend','the CAT']})
ls = ['best','dog']
df[df.col1.str.contains('|'.join(ls))]

换成Polars的话,代码可以这么写:

import polars as pl

# 创建Polars DataFrame
df = pl.DataFrame({'col1':['a red','dog','liked to play','with his best friend','the CAT']})
ls = ['best','dog']

# 用|连接子串,构造正则匹配模式
match_pattern = '|'.join(ls)

# 使用filter结合str.contains筛选符合条件的行
filtered_df = df.filter(pl.col('col1').str.contains(match_pattern))
print(filtered_df)

运行这段代码后,你会得到和Pandas完全一样的结果:包含dog的第二行,以及包含best的第四行。

简单解释下这段Polars代码的逻辑:

  • pl.col('col1'):指定我们要操作的目标列
  • str.contains(match_pattern):检查列中的每个字符串是否包含正则模式里的任意子串,返回布尔Series
  • df.filter(...):根据布尔Series的结果筛选出匹配的行

如果之后你需要忽略大小写匹配(比如想匹配到类似the CAT里的小写子串),只需要给str.contains加个case=False参数就行,比如:

filtered_df = df.filter(pl.col('col1').str.contains(match_pattern, case=False))

备注:内容来源于stack exchange,提问作者frank

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 15:58:13