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

Jingwei Li

Graduate Research assistance at Stony Brook University
linkedin profile url

ProjectPro is an awesome platform that helps me learn much hands-on industrial experience with a step-by-step walkthrough of projects. There are two primary paths to learn: Data Science and Big Data.... Read More

Relevant Projects

A/B Testing Approach for Comparing Performance of ML Models
The objective of this project is to compare the performance of BERT and DistilBERT models for building an efficient Question and Answering system. Using A/B testing approach, we explore the effectiveness and efficiency of both models and determine which one is better suited for Q&A tasks.

AWS MLOps Project to Deploy a Classification Model [Banking]
In this AWS MLOps project, you will learn how to deploy a classification model using Flask on AWS.

MLOps AWS Project on Topic Modeling using Gunicorn Flask
In this project we will see the end-to-end machine learning development process to design, build and manage reproducible, testable, and evolvable machine learning models by using AWS

Build a Logistic Regression Model in Python from Scratch
Regression project to implement logistic regression in python from scratch on streaming app data.

Hands-On Approach to Causal Inference in Machine Learning
In this Machine Learning Project, you will learn to implement various causal inference techniques in Python to determine, how effective the sprinkler is in making the grass wet.

Build ARCH and GARCH Models in Time Series using Python
In this Project we will build an ARCH and a GARCH model using Python

Build an AI Chatbot from Scratch using Keras Sequential Model
In this NLP Project, you will learn how to build an AI Chatbot from Scratch using Keras Sequential Model.

Llama2 Project for MetaData Generation using FAISS and RAGs
In this LLM Llama2 Project, you will automate metadata generation using Llama2, RAGs, and AWS to reduce manual efforts.

Learn Hyperparameter Tuning for Neural Networks with PyTorch
In this Deep Learning Project, you will learn how to optimally tune the hyperparameters (learning rate, epochs, dropout, early stopping) of a neural network model in PyTorch to improve model performance.

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.