如何从可能的字符串列表中替换python中的字符串 [英] How to replace string in python from a list of possible strings

查看:200
本文介绍了如何从可能的字符串列表中替换python中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列看起来像这样的数据:

I have a column of data that looks like this:

df = pd.DataFrame({'Ex1':['apple','apple1','Peear','peAr','b$nana','Bananas'],
'Ex2': ['Applet','banan','apples','PAIR','banana','apple'],
'Ex3':['Pears', 'Banaa', 'Apple', 'apple1', 'pear', 'abanana]}); df

然后我有三个数组,用于将水果类型的拼写错误识别为规范水果类型:

And then I have three arrays that identify misspellings of fruit types as the canonical fruit type:

apple = ['apple1','Applet','apples','Apple']
pear = ['Peear','peAr','PAIR','Pears','p3ar']
banana = ['b$nana','Bananas','banan','Banaa','abanana']

我如何遍历每列以将拼写错误的水果更改为正确的水果. IE.最终的数据帧应如下所示:

How can I iterate over each of the columns to change the misspelled fruit into the correct ones. I.e. the final data frame should look like this:

    Ex1     Ex2     Ex3
0   apple   apple   pear
1   apple   banana  banana
2   pear    apple   apple
3   pear    pear    apple
4   banana  banana  pear
5   banana  apple   banana

我知道我可以使用以下代码实现此结果:

I know I could achieve this outcome with the following code:

replacements = {
    "apple":'apple1',
    "apple":'Applet',
...}

df['Ex1'].replace(replacements, inplace=True)

但是我有1000多个行的列表,并且我不想在replacements中进行每次替换,因为这将花费很多时间.

But I have a list of 1000+ rows and I don't want go through and make each replacement in replacements because that will take a lot of time.

关于以这种方式可以按原样使用我的applepearbanana变量的任何建议?

Any suggestions for doing this in a way that I can use my apple, pear, and banana variables as-is?

推荐答案

仅通过从列表中构造字典即可自动实现涉及拼写错误的手写列表的简单(也许甚至是简单的)方法:

The simple (perhaps even simplistic) approach involving the handwritten lists of misspellings can be automated merely by constructing the dictionary from the lists:

repl={s:n for n,l in [("apple",apple),("pear",pear),("banana",banana)]
      for s in l}

如果正确名称和拼写错误的列表位于某个数据结构(例如包含词典)中,则它们本身可以自动构建. (可以使用globals()locals()作为该词典,但随后必须过滤掉无关的条目.)

The list of correct names and misspellings for each can itself be constructed automatically if they reside in some data structure like a containing dictionary. (It’s possible to use globals() or locals() as that dictionary, but then you have to filter out the extraneous entries.)

这篇关于如何从可能的字符串列表中替换python中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆