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

Python实现自动识别季度首词并批量替换DataFrame列内容

自动适配季度的Survey名称缩写替换方案

问题背景

现有DataFrame的Survey.Name列,每行开头是季度年份标识(如Q321代表2021年第3季度),后续为完整调查名称。原代码通过固定匹配Q321开头的字符串来替换为缩写,但更换季度(如Q421)时需手动修改脚本,需要实现自动识别季度前缀并完成对应缩写替换的逻辑。

原示例数据

Survey Name
0       Q321 Your Voice - Information Tech
1       Q321 Your Voice - Information Tech
2       Q321 Your Voice - Information Tech
3       Q321 Your Voice - Information Tech
4       Q321 Your Voice - Information Tech
                
9630    Q321 Your Voice - Business Group
9631    Q321 Your Voice - Business Group

期望转换结果

Survey Name
0       Q321 YV - IT
1       Q321 YV - IT
2       Q321 YV - IT
3       Q321 YV - IT
4       Q321 YV - IT
                
9630    Q321 YV - BG
9631    Q321 YV - BG

原代码(存在硬编码缺陷)

print(df.loc[:, "Survey.Name"])

# isolate to column of interest and replace commonly incorrect string with the correct output
df.loc[df['Survey.Name'].str.contains('Q321 Your Voice - Information Tech'), 'Survey.Name'] = \
    'Q321 YV - IT'

df.loc[df['Survey.Name'].str.contains('Q321 Your Voice - Business Group'), 'Survey.Name'] = \
    'Q321 YV - BG'

df.loc[df['Survey.Name'].str.contains('Q321 Your Voice - Study Group'), 'Survey.Name'] = \
    'Q321 YV - SG'
        
print(df.loc[:, "Survey.Name"])

解决方案

方案1:正则表达式+映射表

通过正则提取任意季度前缀,结合预定义的名称-缩写映射表,实现批量替换。

import pandas as pd
import re

# 统一管理名称与缩写的对应关系(仅包含季度后的部分)
name_abbr_map = {
    'Your Voice - Information Tech': 'YV - IT',
    'Your Voice - Business Group': 'YV - BG',
    'Your Voice - Study Group': 'YV - SG'
}

# 构建正则模式:匹配开头的季度标识(Q+数字),后续跟空格和完整名称
pattern = r'^(Q\d{2,3}) (' + '|'.join(re.escape(k) for k in name_abbr_map.keys()) + ')$'

# 自定义替换逻辑
def replace_match(match):
    quarter_prefix = match.group(1)
    full_name = match.group(2)
    return f"{quarter_prefix} {name_abbr_map[full_name]}"

# 应用替换
df['Survey.Name'] = df['Survey.Name'].str.replace(pattern, replace_match, regex=True)

print(df['Survey.Name'])

方案2:拆分列拼接法

将原列拆分为季度前缀和调查名称两部分,替换名称后再拼接回去,逻辑更直观。

import pandas as pd

# 定义名称-缩写映射表
name_abbr_map = {
    'Your Voice - Information Tech': 'YV - IT',
    'Your Voice - Business Group': 'YV - BG',
    'Your Voice - Study Group': 'YV - SG'
}

# 按第一个空格拆分,得到季度前缀和完整调查名称
df[['Quarter', 'Full_Name']] = df['Survey.Name'].str.split(n=1, expand=True)

# 替换名称并拼接新的Survey.Name值
df['Survey.Name'] = df['Quarter'] + ' ' + df['Full_Name'].map(name_abbr_map)

# 清理临时生成的列(可选)
df = df.drop(['Quarter', 'Full_Name'], axis=1)

print(df['Survey.Name'])

方案优势

  • 无需硬编码季度标识,自动适配Q321、Q421、Q122等任意格式的季度前缀
  • 映射表集中管理名称对应关系,新增调查类型时只需修改映射表,无需调整核心逻辑
  • 代码复用性强,更换季度数据直接运行即可,无需手动修改脚本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:45:34