The Wayback Machine - https://web.archive.org/web/20240530022122/https://www.geeksforgeeks.org/python-pandas-dataframe-replace/
Open In App

Python | Pandas dataframe.replace()

Last Updated : 01 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Pandas dataframe.replace() function is used to replace a string, regex, list, dictionary, series, number, etc. from a Pandas Dataframe in Python. Every instance of the provided value is replaced after a thorough search of the full DataFrame.

Pandas dataframe.replace() Method Syntax

Syntax: DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’, axis=None) 

Parameters:

  • to_replace : [str, regex, list, dict, Series, numeric, or None] pattern that we are trying to replace in dataframe. 
  • value : Value to use to fill holes (e.g. 0), alternately a dict of values specifying which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed. 
  • inplace : If True, in place. Note: this will modify any other views on this object (e.g. a column from a DataFrame). Returns the caller if this is True. 
  • limit : Maximum size gap to forward or backward fill 
  • regex : Whether to interpret to_replace and/or value as regular expressions. If this is True then to_replace must be a string. Otherwise, to_replace must be None because this parameter will be interpreted as a regular expression or a list, dict, or array of regular expressions.
  • method : Method to use when for replacement, when to_replace is a list. 

Returns: filled : NDFrame

Simple Example of Pandas dataframe.replace()

Here, we are replacing 49.50 with 60.

Python3




import pandas as pd
 
df = {
  "Array_1": [49.50, 70],
  "Array_2": [65.1, 49.50]
}
 
data = pd.DataFrame(df)
 
print(data.replace(49.50, 60))


Output:

   Array_1  Array_2
0     60.0     65.1
1     70.0     60.0

Replace Values in Pandas Dataframe Examples

Here, we are going to see the implementation of dataframe.replace() methods with the help of some examples. For a link to the CSV file Used in Code, click here 

Python3




# importing pandas as pd
import pandas as pd
 
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
 
# Printing the first 10 rows of the data frame for visualization
df[:10]


Output: 

Example 1: Replacing a Single Value

We are going to replace team “Boston Celtics” with “Omega Warrior” in the ‘df’ Dataframe.

Python3




# this will replace "Boston Celtics" with "Omega Warrior"
df.replace(to_replace="Boston Celtics",
           value="Omega Warrior")


Output: 

Example 2: Replacing Two Values with a Single Value

Replacing more than one value at a time. Using python list as an argument We are going to replace team “Boston Celtics” and “Texas” with “Omega Warrior” in the ‘df’ Dataframe. 

Python3




# importing pandas as pd
import pandas as pd
 
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
 
# this will replace "Boston Celtics" and "Texas" with "Omega Warrior"
df.replace(to_replace=["Boston Celtics", "Texas"],
           value="Omega Warrior")


Output: 

Notice the College column in the first row, “Texas” has been replaced with “Omega Warriors”   

Example 3: Replacing Nan With a Random Integer Value

Replace the Nan value in the data frame with the -99999 value. 

Python3




# importing pandas as pd
import pandas as pd
 
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
 
# will replace Nan value in dataframe with value -99999
df.replace(to_replace = np.nan, value =-99999)


Output

Notice all the Nan value in the data frame has been replaced by -99999. Though for practical purposes we should be careful with what value we are replacing nan value.

Example 4: Replacing With Multiple Values

In this example, we are replacing multiple values in a Pandas Dataframe by using dataframe.replace() function.

Python3




# importing pandas as pd
import pandas as pd
 
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
 
df1 = df.replace(['Boston Celtics', 'Amir Johnson', 'R.J. Hunter'],
                 ['Omega Warriors', 'Mitcell Johnson', 'Shivang Thomas'])
df1[:10]


Output

Screenshot-2023-11-20-113533



Previous Article
Next Article

Similar Reads

Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
3 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Replace values in Pandas dataframe using regex
While working with large sets of data, it often contains text data and in many cases, those texts are not pretty at all. The text is often in very messier form and we need to clean those data before we can do anything meaningful with that text data. Mostly the text corpus is so large that we cannot manually list out all the texts that we want to re
4 min read
Replace all the NaN values with Zero's in a column of a Pandas dataframe
Replacing the NaN or the null values in a dataframe can be easily performed using a single line DataFrame.fillna() and DataFrame.replace() method. We will discuss these methods along with an example demonstrating how to use it. DataFrame.fillna(): This method is used to fill null or null values with a specific value. Syntax: DataFrame.fillna(self,
3 min read
Replace Negative Number by Zeros in Pandas DataFrame
In this article, Let's discuss how to replace the negative numbers by zero in Pandas Approach: Import pandas module.Create a Dataframe.Check the DataFrame element is less than zero, if yes then assign zero in this element.Display the final DataFrame First, let's create the dataframe. C/C++ Code # importing pandas module import pandas as pd # Creati
1 min read
Replace negative values with latest preceding positive value in Pandas DataFrame
In this article, we will discuss how to replace the negative value in Pandas DataFrame Column with the latest preceding positive value. While doing this there may arise two situations - Value remains unmodified if no proceeding positive value existsValue update to 0 if no proceeding positive value exists Let's discuss these cases in detail. Case 1:
3 min read
Replace Characters in Strings in Pandas DataFrame
In this article, we are going to see how to replace characters in strings in pandas dataframe using Python. We can replace characters using str.replace() method is basically replacing an existing string or character in a string with a new one. we can replace characters in strings is for the entire dataframe as well as for a particular column. Synta
3 min read
Replace NaN Values with Zeros in Pandas DataFrame
NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results.  [caption width="800"] [/
4 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read