如何在pandas中按字符串列表匹配规则为DataFrame创建新列
实现方案
核心代码(适配大规模数据集的高效向量化实现)
import pandas as pd # 初始数据 d = {'weight': [70, 10, 65, 1], 'String1': ['Labrador is a dog', 'Abyssinian is a cat', 'German Shepard is a dog', 'pigeon is a bird']} df = pd.DataFrame(data=d) # 定义搜索列表 search_list = ['dog','cat'] # 生成animal列 df['animal'] = df['String1'].str.extract(f'({"|".join(search_list)})', expand=False).fillna('other')
执行效果
运行后输出的df和你期望的结构完全一致:
| weight | String1 | animal | |
|---|---|---|---|
| 0 | 70 | Labrador is a dog | dog |
| 1 | 10 | Abyssinian is a cat | cat |
| 2 | 65 | German Shepard is a dog | dog |
| 3 | 1 | pigeon is a bird | other |
说明
- 用
"|".join(search_list)把搜索列表拼接为正则规则dog|cat,支持匹配列表内任意关键词 str.extract为pandas原生向量化操作,逐行返回第一个匹配到的关键词,未匹配的位置返回NaN- 最后通过
fillna('other')把所有未匹配的空缺填充为指定值 - 这套方案性能远高于逐行遍历的
apply写法,完全适配你提到的大规模、逻辑复杂的数据集场景
多匹配场景可选方案
如果存在单条String1同时包含多个搜索关键词的情况,需要保留所有匹配结果,可以用以下写法:
df['animal'] = df['String1'].str.findall(f'({"|".join(search_list)})').str.join(',') df['animal'] = df['animal'].replace('', 'other')
内容的提问来源于stack exchange,提问作者bunti papu
相关产品推荐
相关产品推荐

