How to map values in a Pandas DataFrame?
0

How to map values in a Pandas DataFrame?

This recipe helps you map values in a Pandas DataFrame
In [1]:
## How to map values in a Pandas DataFrame
def Kickstarter_Example_93():
    print()
    print(format('How to map values in a Pandas DataFrame','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd

    # Create dataframe
    raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
                'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'],
                'age': [42, 52, 36, 24, 73],
                'city': ['San Francisco', 'Baltimore', 'Miami', 'Douglas', 'Boston']}
    df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'city'])
    print(); print(df)

    # Create a dictionary of values
    city_to_state = {'San Francisco' : 'California',
                     'Baltimore' : 'Maryland',
                     'Miami' : 'Florida',
                     'Douglas' : 'Arizona',
                     'Boston' : 'Massachusetts'}
    print(); print(city_to_state)

    # Map the values of the city_to_state dictionary to the values in the city variable
    df['state'] = df['city'].map(city_to_state)
    print(); print(df)

Kickstarter_Example_93()
*********************How to map values in a Pandas DataFrame**********************

  first_name last_name  age           city
0      Jason    Miller   42  San Francisco
1      Molly  Jacobson   52      Baltimore
2       Tina       Ali   36          Miami
3       Jake    Milner   24        Douglas
4        Amy     Cooze   73         Boston

{'San Francisco': 'California', 'Baltimore': 'Maryland', 'Miami': 'Florida', 'Douglas': 'Arizona', 'Boston': 'Massachusetts'}

  first_name last_name  age           city          state
0      Jason    Miller   42  San Francisco     California
1      Molly  Jacobson   52      Baltimore       Maryland
2       Tina       Ali   36          Miami        Florida
3       Jake    Milner   24        Douglas        Arizona
4        Amy     Cooze   73         Boston  Massachusetts