如何在Pandas中将字符串匹配文本列的子串替换为对应编码值
Pandas文本匹配替换实现
输入数据
import pandas as pd # 文本-编码映射表 df = pd.DataFrame({ 'text': ['anesthesia code', 'aretic closure', 'nyopia', 'right atrial'], 'codes': [99921, 75454, 75633, 89732] }) # 待处理原始字符串 raw_string = "However, when performed anesthesia code with a formal report, this service may be considered a significant, separately identifiable, and if nyopia, a separately reportable service."
需求为识别字符串中所有与df.text列内容匹配的子串,替换为对应行的编码值,得到目标输出。
实现方式
推荐方案:正则批量替换(性能好、可避免匹配冲突)
先把映射表转成键值对字典,拼接成正则匹配规则,注意要把匹配文本按长度从长到短排序,防止短文本先匹配导致长文本匹配失效,加上单词边界符避免误匹配单词片段:
import re # 构建替换映射 replace_dict = dict(zip(df['text'], df['codes'].astype(str))) # 拼接正则规则,按匹配串长度降序排列 match_pattern = re.compile( r'\b(' + '|'.join(sorted(replace_dict.keys(), key=lambda x: len(x), reverse=True)) + r')\b' ) # 执行替换 output = match_pattern.sub(lambda match_res: replace_dict[match_res.group()], raw_string)
运行后output的结果和预期完全一致:
However, when performed 99921 with a formal report, this service may be considered a significant, separately identifiable, and if 75633, a separately reportable service.
如果不需要做整词匹配,把正则里的
\b去掉即可。
简易方案:逐行遍历替换
如果匹配的文本之间没有包含关系(即不存在某个短文本是另一个长文本的子串),可以直接遍历每一行做字符串替换,写法更简单:
output = raw_string for _, row in df.iterrows(): output = output.replace(row['text'], str(row['codes']))
这个方法逻辑最直观,但如果存在文本嵌套包含的情况会出现替换错误,比如映射里同时存在code和anesthesia code时,先替换code会把长文本拆碎,导致长文本匹配失败。
内容的提问来源于stack exchange,提问作者Shubham Korade
相关产品推荐
相关产品推荐

