How to replace multiple values in a Pandas DataFrame?

This recipe helps you replace multiple values in a Pandas DataFrame

Recipe Objective

Have you ever tried to change multiple values in a dataframe at once? We can do this very easily by replacing the values with another using a simple python code.

So this recipe is a short example on how to replace multiple values in a dataframe. Let's get started.

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

Step 1 - Import the library

import pandas as pd import numpy as np

Here we have imported Pandas and Numpy which are very general libraries.

Step 2 - Setup the Data

Let us create a simple dataset and convert it to a dataframe. This is a dataset of city with different features in it like City_level, City_pool, Rating, City_port and City_Temperature. We have converted this dataset into a dataframe with its features as columns.

city_data = {'city_level': [1, 3, 1, 2, 2, 3, 1, 1, 2, 3], 'city_pool' : ['y','y','n','y','n','n','y','n','n','y'], 'Rating': [1, 5, 3, 4, 1, 2, 3, 5, 3, 4], 'City_port': [0, 1, 0, 1, 0, 0, 1, 1, 0, 1], 'city_temperature': ['low', 'medium', 'medium', 'high', 'low','low', 'medium', 'medium', 'high', 'low']} df = pd.DataFrame(city_data, columns = ['city_level', 'city_pool', 'Rating', 'City_port', 'city_temperature'])

Step 3 - Replacing the values and Printing the dataset

So let us consider that first we want to print the initial dataset and then we want to replace digit 1 (where ever it is present in the dataset) with the string 'one'. Finally we want to view the new dataset with the changes.

So for this we have to use replace function which have 3 important parameters in it.

  • to_replace : In this we have to pass the data of any type(string, int, floatetc) which we want to replace.
  • value : In this we have to pass the data of any type(string, int, floatetc) which we want to insert in the place of the data we want to replace.
  • inplace : It is a boolean parameter with default as False. If true it will keep the changes that is done by the function.

print(df) df = df.replace(1, 'One') print(); print(df)

 

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

Step 5 - Observing the changes in the dataset

Once we run the above code snippet, we will see that the all the 1s in the dataset will be changed to 'one'.

   city_level city_pool  Rating  City_port city_temperature
0           1         y       1          0              low
1           3         y       5          1           medium
2           1         n       3          0           medium
3           2         y       4          1             high
4           2         n       1          0              low
5           3         n       2          0              low
6           1         y       3          1           medium
7           1         n       5          1           medium
8           2         n       3          0             high
9           3         y       4          1              low

  city_level city_pool Rating City_port city_temperature
0        One         y    One         0              low
1          3         y      5       One           medium
2        One         n      3         0           medium
3          2         y      4       One             high
4          2         n    One         0              low
5          3         n      2         0              low
6        One         y      3       One           medium
7        One         n      5       One           medium
8          2         n      3         0             high
9          3         y      4       One              low

Join Millions of Satisfied Developers and Enterprises to Maximize Your Productivity and ROI with ProjectPro - Read ProjectPro Reviews Now!

Download Materials

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

MLOps using Azure Devops to Deploy a Classification Model
In this MLOps Azure project, you will learn how to deploy a classification machine learning model to predict the customer's license status on Azure through scalable CI/CD ML pipelines.

Ola Bike Rides Request Demand Forecast
Given big data at taxi service (ride-hailing) i.e. OLA, you will learn multi-step time series forecasting and clustering with Mini-Batch K-means Algorithm on geospatial data to predict future ride requests for a particular region at a given time.

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.

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

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.

Text Classification with Transformers-RoBERTa and XLNet Model
In this machine learning project, you will learn how to load, fine tune and evaluate various transformer models for text classification tasks.

Build a Review Classification Model using Gated Recurrent Unit
In this Machine Learning project, you will build a classification model in python to classify the reviews of an app on a scale of 1 to 5 using Gated Recurrent Unit.

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

Deploying Machine Learning Models with Flask for Beginners
In this MLOps on GCP project you will learn to deploy a sales forecasting ML Model using Flask.

FEAST Feature Store Example for Scaling Machine Learning
FEAST Feature Store Example- Learn to use FEAST Feature Store to manage, store, and discover features for customer churn prediction machine learning project.