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

使用Pandas替换Excel中macro_id对应值时结果不一致的问题

正则替换macro_id不一致问题的解决

我需要基于电子表格的macro_id列,替换content_text列中的对应macro_id值,但替换结果极不稳定。这些macro_id都是固定长度的数字串,分隔符也统一,但总有部分macro_id无法被替换——既有单条未替换的情况,也有含多个macro_id的文本部分未替换的情况。表格仅4200行左右,排除设备性能问题。

原代码

import pandas as pd
import re

# 读取含11000行的大型电子表格
df = pd.read_excel('testmacros.xlsx')

# 处理'content_text'列的NaN值
df['content_text'] = df['content_text'].fillna('')

# 使用map函数更新'content_text'列的值
s = df.astype({'macro_id': str}).set_index('macro_id')['content_text']

pattern = r'\b(%s)\b' % '|'.join(map(re.escape, s.index))

df['content_text'] = (df['content_text']
                            .str.replace(pattern,
                                         lambda m: s.get(m.group(0)),
                                         regex=True)
                           )

# 保存更新后的电子表格
df.to_excel('updatedmacros.xlsx', index=False)

示例数据

现有数据

macro_idcontent_text
5678111123The Department of Health
5678114567All personnel reporting late should call the 5678114568
5678114568Front desk phone line at 1-555-555-5555
5678112222Patients with a fever 300 should report to 5678114568 and contact 5678111123

预期结果

macro_idcontent_text
5678111123The Department of Health
5678114567All personnel reporting late should call the Front desk phone line at 1-555-555-5555
5678114568Front desk phone line at 1-555-555-5555
5678112222Patients with a fever 300 should report to Front desk phone line at 1-555-555-5555 and contact The Department of Health

排查情况

  • 使用Visual Studio 2019运行代码,未替换的行数波动大,最少8行,最多186行
  • 核对过未替换的macro_id,确认其在表格中存在且对应文本有效
  • 原始数据由Power Query加载,尝试修改字段类型为文本后,问题依旧
  • 尝试将数据粘贴为纯文本保存到xlsx和csv格式,仍无法实现100%替换

解决方法

移除正则表达式中的单词边界匹配\b即可解决问题。

原正则表达式:

pattern = r'\b(%s)\b' % '|'.join(map(re.escape, s.index))

修改为:

pattern = r'(%s)' % '|'.join(map(re.escape, s.index))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:28:19