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

Build Regression Models in Python for House Price Prediction
In this Machine Learning Regression project, you will build and evaluate various regression models in Python for house price prediction.

Mastering A/B Testing: A Practical Guide for Production
In this A/B Testing for Machine Learning Project, you will gain hands-on experience in conducting A/B tests, analyzing statistical significance, and understanding the challenges of building a solution for A/B testing in a production environment.

Credit Card Fraud Detection as a Classification Problem
In this data science project, we will predict the credit card fraud in the transactional dataset using some of the predictive models.

Build a CNN Model with PyTorch for Image Classification
In this deep learning project, you will learn how to build an Image Classification Model using PyTorch CNN

Build Real Estate Price Prediction Model with NLP and FastAPI
In this Real Estate Price Prediction Project, you will learn to build a real estate price prediction machine learning model and deploy it on Heroku using FastAPI Framework.

PyTorch Project to Build a GAN Model on MNIST Dataset
In this deep learning project, you will learn how to build a GAN Model on MNIST Dataset for generating new images of handwritten digits.

Build a Similar Images Finder with Python, Keras, and Tensorflow
Build your own image similarity application using Python to search and find images of products that are similar to any given product. You will implement the K-Nearest Neighbor algorithm to find products with maximum similarity.

Stock Price Prediction Project using LSTM and RNN
Learn how to predict stock prices using RNN and LSTM models. Understand deep learning concepts and apply them to real-world financial data for accurate forecasting.

OpenCV Project for Beginners to Learn Computer Vision Basics
In this OpenCV project, you will learn computer vision basics and the fundamentals of OpenCV library using Python.

Build a Customer Churn Prediction Model using Decision Trees
Develop a customer churn prediction model using decision tree machine learning algorithms and data science on streaming service data.