如何使用 str.replace 一次替换多个对? [英] How to use str.replace to replace multiple pairs at once?
本文介绍了如何使用 str.replace 一次替换多个对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我正在使用以下代码进行替换,这有点麻烦:
Currently I am using the following code to make replacements which is a little cumbersome:
df1['CompanyA'] = df1['CompanyA'].str.replace('.','')
df1['CompanyA'] = df1['CompanyA'].str.replace('-','')
df1['CompanyA'] = df1['CompanyA'].str.replace(',','')
df1['CompanyA'] = df1['CompanyA'].str.replace('ltd','limited')
df1['CompanyA'] = df1['CompanyA'].str.replace('&','and')
df1['Address1A'] = df1['Address1A'].str.replace('.','')
df1['Address1A'] = df1['Address1A'].str.replace('-','')
df1['Address1A'] = df1['Address1A'].str.replace('&','and')
df1['Address1A'].str.replace(r'\brd\b', 'road')
df1['Address2A'] = df1['Address2A'].str.replace('.','')
df1['Address2A'] = df1['Address2A'].str.replace('-','')
df1['Address2A'] = df1['Address2A'].str.replace('&','and')
df1['Address2A'].str.replace(r'\brd\b', 'road')
为了使即时更改更容易,我的理想情况是这样的:
In order to make changing on the fly easier my ideal scenario would be something like:
df1['CompanyA'] = df1['CompanyA'].str.replace(('&','and'), ('.', ''), ('-','')....)
df1['Address1A'] = df1['Address1A'].str.replace(('&','and'), ('.', ''), ('-','')....)
df1['Address2A'] = df1['Address2A'].str.replace(('&','and'), ('.', ''), ('-','')....)
这样我就可以输入/更改我想为特定列替换的内容,而无需调整多行代码.
This is so I could just input/change what I wanted to replace for a particular column without having to adjust multiple lines of code.
这可能吗?
推荐答案
您可以创建字典并将其传递给函数 replace()
,而无需多次链接或命名函数.
You can create a dictionary and pass it to the function replace()
without needing to chain or name the function so many times.
replacers = {',':'','.':'','-':'','ltd':'limited'} #etc....
df1['CompanyA'] = df1['CompanyA'].replace(replacers)
这篇关于如何使用 str.replace 一次替换多个对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文