Mapping values in a Pandas Dataframe

In this tutorial, you’ll learn how to map values in a pandas data frame. Sometimes, it is important to map the values of one column to the other. To map values, we use the map() function. This function can take three different shapes i.e., dictionaries, functions, and series. It depends on what you pass into the method.

Using map() method to map values

Steps to map values

  1. Import the library
  2. Building the data
  3. Mapping the values

Step 1: Import the library

import pandas as pd

We have imported the required library.

Step 2: Building the data

Let’s take a sample data frame to work with,

data = pd.DataFrame({'Teams': ['A', 'B', 'C', 'D'],
                     'Leaders': ['Mike', 'Riya', 'Nelson', 'Adam'],
                   'Scores': ['40', '38', '30', '45'],
                   'GPA': ['8.5', '7.4', '6.2', '7.6']})


  Teams Leaders Scores  GPA
0     A    Mike     40  8.5
1     B    Riya     38  7.4
2     C  Nelson     30  6.2
3     D    Adam     45  7.6

Step 3: Mapping the values

Now, define a dictionary with keys as already existing values in the data frame and the key values as the values that are to be added.

dict= {'Mike':'Cooper','Riya':'Sheldon','Nelson':'Mandela','Adam':'Smith'}

Using map() function, we map the column ‘Leaders’ with ‘Last_names’.

data['Last_names'] = data['Leaders'].map(dict)


  Teams Leaders Scores  GPA Last_names
0     A    Mike     40  8.5     Cooper
1     B    Riya     38  7.4    Sheldon
2     C  Nelson     30  6.2    Mandela
3     D    Adam     45  7.6      Smith

Here, we can see that a new column has been added at the end with the name ‘Last_names’. The inside process is matching the values of the column ‘Leaders’ with the keys of the dictionary ‘dict’. So, we can map the values of any column with new ones by using map() method.

Continue reading,

Leave a Reply

Your email address will not be published. Required fields are marked *