我想根据列内容中的匹配值和 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['描述']))
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 列中的多个值,但它们似乎都没有改变。
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