Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The process of utilizing the map function to map a pandas column using a dictionary can be broken down into the following steps:

  1. Create a dictionary that maps values from the current column to the desired values.

  2. Use the map function on the column and pass in the dictionary as an argument.

For example, let's say we have a pandas dataframe with a column of country names spelled out in full:

import pandas as pd

df = pd.DataFrame({'country':['United States', 'Canada', 'Mexico']})

If we wanted to map these country names to their corresponding two-letter ISO codes, we could create a dictionary like so:

iso_codes = {'United States': 'US', 'Canada': 'CA', 'Mexico': 'MX'}

We could then use the map function to apply this dictionary to the 'country' column:

df['iso_code'] = df['country'].map(iso_codes)

This would result in the following dataframe:

        country iso_code
0  United States       US
1         Canada       CA
2         Mexico       MX