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

如何用Pandas检测字符串列中的颜色词并替换及添加标记列

解决DataFrame颜色字符串匹配替换问题

需求说明

  • 给定颜色列表:color_list = ['red', 'black', 'white', "a'pink", 'blue']
  • 处理包含复杂字符串的DataFrame列colors,完成两个任务:
    1. 若字符串包含列表中的颜色词,将整串替换为该颜色词
    2. 添加一列is it,标记是否成功匹配替换(匹配为True,否则为False)

示例输入

import pandas as pd

color_list = ['red', 'black', 'white', "a'pink", 'blue']
data = ['on red', 'aup red gone', 'black with bi', "ao a' pink", 'dgfh blu', 'a black pen']
df = pd.DataFrame(data, columns=['colors'])

print("原始DataFrame:")
print(df)

输出:

原始DataFrame:
          colors
0         on red
1   aup red gone
2  black with bi
3     ao a' pink
4       dgfh blu
5    a black pen

期望输出

colors  is it
0       red   True
1       red   True
2     black   True
3   a' pink   True
4  dgfh blu  False
5     black   True

解决方案代码

import pandas as pd
import re

color_list = ['red', 'black', 'white', "a'pink", 'blue']
# 构建正则匹配模式:转义特殊字符,同时兼容"a'pink"和"a' pink"的匹配
pattern = re.compile(r'\b(' + '|'.join(re.escape(color).replace("a'pink", r"a'\s?pink") for color in color_list) + r')\b', re.IGNORECASE)

data = ['on red', 'aup red gone', 'black with bi', "ao a' pink", 'dgfh blu', 'a black pen']
df = pd.DataFrame(data, columns=['colors'])

# 定义匹配替换逻辑
def match_and_replace(s):
    match_result = pattern.search(s)
    if match_result:
        # 调整匹配结果格式,和期望输出一致
        matched_color = match_result.group().replace("a'pink", "a' pink")
        return (matched_color, True)
    return (s, False)

# 应用逻辑到DataFrame,拆分结果为两列
df[['colors', 'is it']] = df['colors'].apply(lambda x: pd.Series(match_and_replace(x)))

print("处理后的DataFrame:")
print(df)

代码说明

  1. 正则模式处理:

    • 用re.escape()转义颜色词中的特殊字符(比如'),避免正则语法冲突
    • 针对a'pink调整规则,允许中间出现空格(a'\s?pink),兼容示例中的ao a' pink场景
    • 用\b确保匹配完整单词,避免误匹配(比如不会把blu当成blue)
  2. 匹配替换逻辑:

    • 遍历字符串查找颜色词,匹配成功则返回对应颜色(调整格式符合期望)和True
    • 未匹配则返回原字符串和False
  3. DataFrame应用:

    • 通过apply()将逻辑批量应用到colors列,用pd.Series把结果拆分为两列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:47:21