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

Python如何判断pandas DataFrame列是否含列表中词汇并生成匹配新列

你可以使用pandas的str.extract()方法结合正则表达式完成需求,它会自动提取匹配到的第一个关键词,未匹配的内容默认返回NaN,刚好符合你的预期输出。

完整实现代码

import pandas as pd

# 初始化数据
data = {'Colour':['Blue andtext', 'Greys', 'Potato', 'Yellow','Tree'],
        'Values':[20, 21, 19, 18,44]}
df2 = pd.DataFrame(data)
# 目标颜色列表
colours = ['Blue','Grey','Yellow']

# 核心逻辑:拼接正则匹配规则,提取匹配颜色
pattern = '|'.join(colours)
df2['Actualcolour'] = df2['Colour'].str.extract(f'({pattern})', expand=False)

# 输出查看结果
print(df2)

运行输出结果

Colour  Values Actualcolour
0  Blue andtext      20         Blue
1         Greys      21         Grey
2        Potato      19          NaN
3        Yellow      18       Yellow
4          Tree      44          NaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:18:02