使用 Pandas 替换句子中的特定值

问题描述 投票:0回答:1

我想根据列内容中的匹配值和 marcros.xlsx 的列 ID 中的 ID,仅将 Articles.xlsx 的“内容”列中的特定值替换为“macros.xlsx”的“描述”列中的值。

文章

文章ID 内容_文本
第22条 123将于1月1日开始工作。
第23条 345 将于 1 月 15 日开始与 678 一起工作

身份证 描述
123 约翰
345 马歇尔
678 温迪

我尝试使用下面的语法,希望看到这样的内容:

更新文章

文章

文章ID 内容_文本
第22条 约翰将于 1 月 1 日开始工作。
第23条 Marshall 将于 1 月 15 日开始与 Wendy 一起工作

将 pandas 导入为 pd

阅读大篇

df_large = pd.read_excel('文章.xlsx')

阅读小文

df_small = pd.read_excel('macros.xlsx')

创建一个字典,将小型电子表格中的值映射到相应的替换值

replacement_dict = dict(zip(df_small['ID'], df_small['描述']))

使用地图功能更新大型电子表格 H 列中的值

df_large['content_text'] = df_large['content_text'].map(lambda x: replacement_dict.get(x, x))

保存更新后的大型电子表格

df_large.to_excel('updated_Articles.xlsx',index=False)

相反,我只是获取文章表中的原始数据,没有任何更改。某些内容文本可能是一个很长的段落,其中也包含 ID 列中的多个值,但它们似乎都没有改变。

python pandas xlsx
1个回答
0
投票

您可以使用正则表达式

str.replace
:

import re

s = df_small.astype({'ID': str}).set_index('ID')['Description']

pattern = r'\b(%s)\b' % '|'.join(s.index)
# '\\b(123|345|678)\\b'

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

输出:

   Article ID                                          Content_Text
0  Article 22                 John will begin working on January 1.
1  Article 23  Marshall will begin working on January 15 with Wendy
© www.soinside.com 2019 - 2024. All rights reserved.