Skip to content Skip to sidebar Skip to footer

Replace String With Value Of Dictionary

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 th

Solution 1:

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)

Solution 2:

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)

Post a Comment for "Replace String With Value Of Dictionary"