将字符串替换为Dictionary的值

2024-09-29 19:28:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我会尽量简化。我有一个按州列出的数据框。有些州是缩写,有些不是。我想用缩写代替全州名(例如:新泽西州到新泽西州)。在

我发现了一个很酷的模块“US”foundhere,它列出了字典中所有的状态及其缩写。我想做的是用缩写代替全名。在

代码:

import pandas as pd
import numpy as np
import us
dfp = pd.DataFrame({'A' : [np.NaN,np.NaN,3,4,5,5,3,1,5,np.NaN], 
                    'B' : [1,0,3,5,0,0,np.NaN,9,0,0], 
                    'C' : ['Pharmacy of Oklahoma','NY Pharma','NJ Pharmacy','Idaho Rx','CA Herbals','Florida Pharma','AK RX','Ohio Drugs','PA Rx','USA Pharma'], 
                    'D' : [123456,123456,1234567,12345678,12345,12345,12345678,123456789,1234567,np.NaN],
                    'E' : ['Assign','Unassign','Assign','Ugly','Appreciate','Undo','Assign','Unicycle','Assign','Unicorn',]})
print(dfp)

statez = us.states.mapping('abbr', 'name')
lst_of_abbrv = statez.keys()
lst_of_states = statez.values()

phrase = "Pharmacy of Oklahoma"

for x in phrase.split():
    if x in lst_of_states:
        x= x.replace(x, 'State')
        print(phrase.split())

现在我唯一能做的就是用一个字符串替换成“State”。我怎样用字典里的缩写来代替这个名字?我试过想要一些类似x= x.replace(x, lst_of_abbrv)的东西 但它会出错,因为你显然不能用dict_键代替。在

如果您能够解释如何将此应用于Dataframe的“C”列,则需要额外说明


Tags: ofimport字典asnpnanpdus
2条回答

以下是完整的解决方案:

# Note the difference here
statez = us.states.mapping('name', 'abbr')
lst_of_states = statez.keys()
lst_of_abbrv = statez.values()

def sentence_with_states_abbreviated(phrase):
    words = phrase.split()
    for (i,word) in enumerate(words):
        if word in lst_of_states:
            words[i] = statez[word]
    return ' '.join(words)

dfp['C'] = dfp['C'].apply(sentence_with_states_abbreviated)

首先,我将定义一个函数,它将替换字符串中状态的全名(如果存在的话),或者返回原始字符串。在

def replace_states(company):
    # find all states that exist in the string
    state_found = filter(lambda state: state in company, statez.keys())

    # replace each state with its abbreviation
    for state in state_found:
        company = company.replace(state, statez[state])
    # return the modified string (or original if no states were found)
    return company

然后可以将此函数应用于dataframe的整个列

^{pr2}$

相关问题 更多 >

    热门问题