繁体   English   中英

Pandas 用其他列中的值替换部分字符串

[英]Pandas Replace part of string with value from other column

我有一个 dataframe (参见示例,因为敏感数据),带有一个完整的术语(字符串),一个包含完整术语和缩写(字符串)的文本片段(一个大字符串)。 我一直在努力解决如何用相应的缩写替换文本片段中的完整术语。 任何人都可以帮忙吗? 例子:

    term                      text_snippet                                 abbr
0   aanvullend onderzoek      aanvullend onderzoek is vereist om...        ao/

所以我想结束:

    term                      text_snippet                                 abbr
0   aanvullend onderzoek      ao/ is vereist om...                         ao/

您可以使用apply并用缩写替换术语:

df['text_snippet'] = df.apply(
    lambda x: x['text_snippet'].replace(x['term'], x['abbr']), axis=1)

df

Output:

                   term          text_snippet abbr
0  aanvullend onderzoek  ao/ is vereist om...  ao/

这是一个解决方案。 我编了一个简单的dataframe:

df = pd.DataFrame({'term':['United States of America','Germany','Japan'],
              'text_snippet':['United States of America is in America',
                           'Germany is in Europe',
                           'Japan is in Asia'],
              'abbr':['USA','DE','JP']})
df

Dataframe 之前的解决方案:

              term              text_snippet                            abbr
0   United States of America    United States of America is in America  USA
1   Germany                     Germany is in Europe                    DE
2   Japan                       Japan is in Asia                        JP

在每一行上使用 apply function:

df['text_snippet'] = df.apply(lambda row : row['text_snippet'].replace(row['term'],row['abbr']), axis= 1 )

Output:

                term            text_snippet        abbr
0   United States of America    USA is in America   USA
1   Germany                     DE is in Europe     DE
2   Japan                       JP is in Asia       JP

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM