Replace String with Value of Dictionary

2019-07-23 15:20发布

I will simplify as much as possible. I have a DataFrame with a list of businesses by state. Some States are abbreviated, some are not. I want to replace the full state name with the Abbreviation (ex: New Jersey to NJ).

I found a cool module "US" found here that lists all the states and their abbreviations in a dictionary. What I would like to do is replace the full name with the abbreviations.

code:

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

Right now the only thing I'm able to do is use a string and replace it with the word "State". How do i replace the name with the abbreviations from the dictionary? I've tried and want something like x= x.replace(x, lst_of_abbrv) but it errors because you obviously can't replace with dict_keys.

Extra points if you are able to explain how to apply this to column "C" of the Dataframe

2条回答
叛逆
2楼-- · 2019-07-23 15:30

First I would define a function that would replace the full name of states in a string if any exist or return the original string.

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

then you can apply this function to the entire column of the dataframe

dfp['C'] = dfp['C'].map(replace_states)
查看更多
We Are One
3楼-- · 2019-07-23 15:52

Here is the complete solution:

# 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)
查看更多
登录 后发表回答