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

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

AWS Project to Build and Deploy LSTM Model with Sagemaker
In this AWS Sagemaker Project, you will learn to build a LSTM model on Sagemaker for sales forecasting while analyzing the impact of weather conditions on Sales.

Machine Learning Project to Forecast Rossmann Store Sales
In this machine learning project you will work on creating a robust prediction model of Rossmann's daily sales using store, promotion, and competitor data.

Insurance Pricing Forecast Using XGBoost Regressor
In this project, we are going to talk about insurance forecast by using linear and xgboost regression techniques.

House Price Prediction Project using Machine Learning in Python
Use the Zillow Zestimate Dataset to build a machine learning model for house price prediction.

Microsoft Fabric Project to Build a Financial Reporting Agent
In this Microsoft Fabric project, you'll build a financial reporting agent that simplifies data management, automates analysis, and delivers real-time dashboards for wealth advisors and their clients.

Learn to Build an End-to-End Machine Learning Pipeline - Part 1
In this Machine Learning Project, you will learn how to build an end-to-end machine learning pipeline for predicting truck delays, addressing a major challenge in the logistics industry.

Build Time Series Models for Gaussian Processes in Python
Time Series Project - A hands-on approach to Gaussian Processes for Time Series Modelling in Python

Learn How to Build a Logistic Regression Model in PyTorch
In this Machine Learning Project, you will learn how to build a simple logistic regression model in PyTorch for customer churn prediction.

Build a Graph Based Recommendation System in Python-Part 2
In this Graph Based Recommender System Project, you will build a recommender system project for eCommerce platforms and learn to use FAISS for efficient similarity search.

Medical Image Segmentation Deep Learning Project
In this deep learning project, you will learn to implement Unet++ models for medical image segmentation to detect and classify colorectal polyps.