如何匹配DataFrame text列指定词替换后生成新行添加到另一DataFrame
Pandas 双DataFrame文本匹配替换追加方案
你可以直接用下面的pandas操作实现需求,无需手动逐行遍历全量数据,运行效率更高:
- 首先定义匹配替换映射规则,支持批量设置多组目标词替换逻辑
- 先筛选出
text列包含目标词的行,仅对目标行做修改 - 最后将处理后的行批量追加到
dataframe2中
import pandas as pd # 替换规则配置,可按需新增多组 # 格式: {目标词: (替换后的新词, 新行的abstract字段值)} replace_config = { "beautiful": ("bf", "bf") } target_word_list = list(replace_config.keys()) # 筛选dataframe1中text列包含任意目标词的行,自动跳过空值 matched_rows = dataframe1[dataframe1['text'].str.contains('|'.join(target_word_list), na=False)].copy() # 对匹配到的行按规则修改字段 for _, row in matched_rows.iterrows(): for target_word, (new_word, new_abstract) in replace_config.items(): if target_word in row['text']: # 替换text中的目标词 matched_rows.loc[_, 'text'] = row['text'].replace(target_word, new_word) # 替换abstract matched_rows.loc[_, 'abstract'] = new_abstract # 替换label为原目标词 matched_rows.loc[_, 'label'] = target_word # 追加到dataframe2 dataframe2 = pd.concat([dataframe2, matched_rows], ignore_index=True)
如果存在单条text同时包含多个目标词的情况,可自行调整匹配优先级逻辑,比如只处理第一个匹配到的目标词,或者按顺序全量替换即可。
内容的提问来源于stack exchange,提问作者mandana hosseini
相关产品推荐
相关产品推荐

