How to map values in a Pandas DataFrame?

This recipe helps you map values in a Pandas DataFrame

Recipe Objective - How to map values in a Pandas DataFrame?

We sometimes use Python Pandas to map values to other values in Python, i.e., values of a feature with values of another feature.

This recipe will show you how to perform Pandas Dataframe map column values.

Get Closer To Your Dream of Becoming a Data Scientist with 70+ Solved End-to-End ML Projects

Steps For Python Pandas Map Column Values

The following steps will help you understand how to map Pandas dataframe, i.e., map column values in Pandas Dataframe.

Step 1 - Import the library

import pandas as pd

We have imported the Pandas library, which is needed to perform Pandas Dataframe map values.

Step 2 - Setting up the Data

We have created a dataset by making a dictionary with features and passing it through the dataframe function. 

raw_data = {"first_name": ["Sheldon", "Raj", "Leonard", "Howard", "Amy"], "last_name": ["Copper", "Koothrappali", "Hofstadter", "Wolowitz", "Fowler"], "age": [42, 38, 36, 41, 35], "Comedy_Score": [9, 7, 8, 8, 5], "Rating_Score": [25, 25, 49, 62, 70]} df = pd.DataFrame(raw_data, columns = ["first_name", "last_name", "age", "Comedy_Score", "Rating_Score"]) print(df)

Explore More Data Science and Machine Learning Projects for Practice. Fast-Track Your Career Transition with ProjectPro

Step 3 - Pandas Dataframe: Map Values

First, we have made a dictionary with the values mapped with other values, such that the first value is of feature first_name and the next is of new feature subjects. 

Subjects =
{"Sheldon" : "Science", "Raj" : "Chemistry", "Leonard" : "Maths", "Howard" : "Astronaut", "Amy" : "Science"} print(Subjects) 

Now, we have created a function to map the values of different columns. 

df["Subjects"] = df["first_name"].map(Subjects) print(df) 

So the output comes as-

 first_name     last_name  age  Comedy_Score  Rating_Score

0    Sheldon        Copper   42             9            25

1        Raj  Koothrappali   38             7            25

2    Leonard    Hofstadter   36             8            49

3     Howard      Wolowitz   41             8            62

4        Amy        Fowler   35             5            70

 

{"Sheldon": "Science", "Raj": "Chemistry", "Leonard": "Maths", "Howard": "Astronaut", "Amy": "Science"}

 

  first_name     last_name  age  Comedy_Score  Rating_Score   Subjects

0    Sheldon        Copper   42             9            25    Science

1        Raj  Koothrappali   38             7            25  Chemistry

2    Leonard    Hofstadter   36             8            49      Maths

3     Howard      Wolowitz   41             8            62  Astronaut

4        Amy        Fowler   35             5            70    Science

Pandas DataFrame- Map Column Values to Lowercase

To map values in a Pandas DataFrame to lowercase, you can use the str.lower() method. The str.lower() method converts a string to lowercase.

The following code shows how to map values in a Pandas DataFrame to lowercase-

import pandas as pd

df = pd.DataFrame({'A': ['Hello', 'World', 'PYTHON']})

# Map the values in column A to lowercase

df['A'] = df['A'].str.lower()

print(df)

The output of the code is shown below:

       A

0   hello

1   world

2   python





Download Materials


What Users are saying..

profile image

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

BERT Text Classification using DistilBERT and ALBERT Models
This Project Explains how to perform Text Classification using ALBERT and DistilBERT

Build an End-to-End AWS SageMaker Classification Model
MLOps on AWS SageMaker -Learn to Build an End-to-End Classification Model on SageMaker to predict a patient’s cause of death.

Build a Churn Prediction Model using Ensemble Learning
Learn how to build ensemble machine learning models like Random Forest, Adaboost, and Gradient Boosting for Customer Churn Prediction using Python

NLP Project for Multi Class Text Classification using BERT Model
In this NLP Project, you will learn how to build a multi-class text classification model using using the pre-trained BERT model.

Census Income Data Set Project-Predict Adult Census Income
Use the Adult Income dataset to predict whether income exceeds 50K yr based oncensus data.

Build an AI Email Assistant Using AWS Lambda,Bedrock and OpenAI
In this AI project, you will learn to design and deploy an AI-powered Gmail workflow that automatically classifies emails by urgency, applies contextual organization with labels, drafts responses, and delivers actionable summaries.

PyTorch Project to Build a LSTM Text Classification Model
In this PyTorch Project you will learn how to build an LSTM Text Classification model for Classifying the Reviews of an App .

Build a Autoregressive and Moving Average Time Series Model
In this time series project, you will learn to build Autoregressive and Moving Average Time Series Models to forecast future readings, optimize performance, and harness the power of predictive analytics for sensor data.

Linear Regression Model Project in Python for Beginners Part 1
Machine Learning Linear Regression Project in Python to build a simple linear regression model and master the fundamentals of regression for beginners.

Build an Image Classifier for Plant Species Identification
In this machine learning project, we will use binary leaf images and extracted features, including shape, margin, and texture to accurately identify plant species using different benchmark classification techniques.