Skip to content Skip to sidebar Skip to footer

Map US State Name To Two Letter Acronyms That Was Given In Dictionary Separately

Suppose now I have a dataframe with 2 columns: State and City. Then I have a separate dict with the two-letter acronym for each state. Now I want to add a third column to map stat

Solution 1:

For one, it's probably easier to store the key-value pairs like state name: abbreviation in your dictionary, like this:

state_2 = {'Ohio': 'OH', 'Illinois': 'IL', 'California': 'CA', 'Texas': 'TX'}

You can achieve this easily:

state_2 = {state: abbrev for abbrev, state in state_2.items()}

Using pandas.DataFrame.map:

>>> state_city['abbrev'] = state_city['State'].map(state_2)
>>> state_city
          City       State abbrev
0    Cleveland        Ohio     OH
1      Chicago    Illinois     IL
2   Naperville    Illinois     IL
3     Columbus        Ohio     OH
4      Houston       Texas     TX
5  Los Angeles  California     CA
6    San Diego  California     CA

Solution 2:

I do agree with @blacksite that the state_2 dictionary should map its values like that:

state_2 = {'Ohio': 'OH','Illinois': 'IL','California': 'CA','Texas': 'TX'}

Then using pandas.DataFrame.replace

state_city['state_2letter'] = state_city.State.replace(state_2)
state_city

|-|State      |City         |state_2letter|
|-|-----      |------       |----------|
|0| Ohio      | Cleveland   |   OH|
|1| Illinois  | Chicago     |   IL|
|2| Illinois  | Naperville  |   IL|
|3| Ohio      | Columbus    |   OH|
|4| Texas     | Houston     |   TX|
|5| California| Los Angeles |   CA|
|6| California| San Diego   |   CA|

Post a Comment for "Map US State Name To Two Letter Acronyms That Was Given In Dictionary Separately"