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

如何用Python提取字符串中首次出现的指定颜色至MainColor列?

Python提取首次出现的指定颜色至MainColor列

实现方案

核心思路

定义目标颜色集合,对表格中Colors列的每个字符串,按颜色在字符串中出现的先后顺序,返回第一个匹配到的指定颜色。

代码实现(基于Pandas处理表格)

import pandas as pd

# 指定需要匹配的颜色集合
target_colors = {'Grey', 'Black', 'Blue', 'White'}

def get_first_matched_color(text):
    # 遍历颜色,返回字符串中第一个出现的目标颜色
    for color in target_colors:
        if color in text:
            return color
    return None  # 无匹配时返回None

# 构造示例数据
sample_data = {
    'Colors': [
        'Grey',
        'Black',
        'Blue Black',
        'The item color is White Black'
    ]
}
df = pd.DataFrame(sample_data)

# 生成MainColor列
df['MainColor'] = df['Colors'].apply(get_first_matched_color)

# 查看结果
print(df)

代码说明

  • target_colors:存储需要匹配的所有颜色,集合结构不影响匹配逻辑,因为是按字符串内的出现顺序判断。
  • get_first_matched_color:针对输入文本,逐个检查目标颜色是否存在,返回第一个命中的颜色。
  • apply方法:批量对Colors列的每一行应用匹配函数,生成MainColor列。

运行结果

输出的DataFrame与预期完全一致:

Colors MainColor
0                           Grey      Grey
1                           Black     Black
2                      Blue Black      Blue
3  The item color is White Black     White

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:34:51