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

如何在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和你期望的结构完全一致:

weightString1animal
070Labrador is a dogdog
110Abyssinian is a catcat
265German Shepard is a dogdog
31pigeon is a birdother

说明

  • 用"|".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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 17:45:01