用字典的值替换字符串

Replace String with Value of Dictionary

我会尽量简化。我有一个 DataFrame,其中包含各州的企业列表。有些州是缩写的,有些则不是。我想用缩写替换完整的州名称(例如:新泽西州到新泽西州)。

我找到了一个很酷的模块 "US" here,它在字典中列出了所有州及其缩写。我想做的是用缩写替换全名。

代码:

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_keys 替换。

如果您能够解释如何将其应用于 Dataframe

的第 "C" 列,则加分

完整的解决方案如下:

# 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)

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

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

然后您可以将此函数应用于数据框的整个列

dfp['C'] = dfp['C'].map(replace_states)