如何在DataFrame中查找特定值?附模糊匹配场景示例
在DataFrame中匹配特定前缀的值(类似SQL的%通配符)
假设你的DataFrame有一列存储账号信息,比如示例中的account列,以下是几种实现需求的方法:
1. 使用str.startswith精确匹配前缀
这是最直接的方式,专门用来匹配以指定字符串开头的内容,对应你需求中的Acc001%匹配逻辑:
import pandas as pd # 构造示例DataFrame data = {'account': ['Acc001', 'Acc001(1)', 'Acc002', 'Acc003', 'Acc003(1)']} df = pd.DataFrame(data) # 筛选以"Acc001"开头的行 filtered_df = df[df['account'].str.startswith('Acc001')] # 提取结果为集合 matched_values = set(filtered_df['account']) print(matched_values) # 输出: {'Acc001', 'Acc001(1)'}
2. 用正则表达式适配通配符%
如果需要兼容类似SQL的%通配符写法(比如把搜索词Acc001%直接转换成正则规则),可以将%替换为正则中的.*(匹配任意字符),再用str.contains实现:
search_term = 'Acc001%' # 把SQL通配符转为正则表达式,加^限定开头避免误匹配 regex_pattern = f'^{search_term.replace("%", ".*")}' filtered_df = df[df['account'].str.contains(regex_pattern, regex=True)] matched_values = set(filtered_df['account'])
3. 使用query方法(类SQL语法)
如果你习惯SQL风格的查询,可以用query方法结合字符串方法:
filtered_df = df.query("account.str.startswith('Acc001')") matched_values = set(filtered_df['account'])
注意事项
- 确保目标列是字符串类型,如果不是,先转换:
df['account'] = df['account'].astype(str) - 如果需要匹配任意位置包含指定字符的内容(比如
%Acc001%),去掉正则中的^即可,或者直接用df[df['account'].str.contains('Acc001')]
内容的提问来源于stack exchange,提问作者beginofwork
相关产品推荐
相关产品推荐

