The Wayback Machine - https://web.archive.org/web/20241020192720/https://www.geeksforgeeks.org/replace-values-in-pandas-dataframe-using-regex/
Open In App

Replace values in Pandas dataframe using regex

Last Updated : 31 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 replace. So in those cases, we use regular expressions to deal with such data having some pattern in it.

We have already discussed in the previous article how to replace some known string values in dataframe. In this post, we will use regular expressions to replace strings that have some pattern to it.

Using Dataframe.replace() Function

Problem #1: You are given a dataframe that contains the details about various events in different cities. For those cities which start with the keyword ‘New’ or ‘new’, change it to ‘New_’.

Solution: We are going to use regular expression to detect such names and then we will use Dataframe.replace() function to replace those names.

Python3




# importing pandas as pd
import pandas as pd
 
# Let's create a Dataframe
df = pd.DataFrame({'City':['New York', 'Parague', 'New Delhi', 'Venice', 'new Orleans'],
                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy', 'Tech_Summit'],
                    'Cost':[10000, 5000, 15000, 2000, 12000]})
 
# Let's create the index
index_ = [pd.Period('02-2018'), pd.Period('04-2018'),
          pd.Period('06-2018'), pd.Period('10-2018'), pd.Period('12-2018')]
 
# Set the index
df.index = index_
 
# Let's print the dataframe
print(df)


Output :

                City        Event   Cost
2018-02 New York Music 10000
2018-04 Parague Poetry 5000
2018-06 New Delhi Theatre 15000
2018-10 Venice Comedy 2000
2018-12 new Orleans Tech_Summit 12000

Now we will write the regular expression to match the string and then we will use Dataframe.replace() function to replace those names.

Python3




# replace the matching strings
df_updated = df.replace(to_replace ='[nN]ew', value = 'New_', regex = True)
 
# Print the updated dataframe
print(df_updated)


Output :

                 City        Event   Cost
2018-02 New_ York Music 10000
2018-04 Parague Poetry 5000
2018-06 New_ Delhi Theatre 15000
2018-10 Venice Comedy 2000
2018-12 New_ Orleans Tech_Summit 12000

As we can see in the output, the old strings have been replaced with the new ones successfully.  

Problem #2: You are given a dataframe containing details about various events in different cities. The names of certain cities contain some additional details enclosed in a bracket. Search for such names and remove the additional details.

Solutioncontaining: For this task, we will write our own customized function using regular expression to identify and update the names of those cities. Additionally, We will use Dataframe.apply() function to apply our customized function on each values the column.

Python3




# importing pandas as pd
import pandas as pd
 
# Let's create a Dataframe
df = pd.DataFrame({'City':['New York (City)', 'Parague', 'New Delhi (Delhi)', 'Venice', 'new Orleans'],
                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy', 'Tech_Summit'],
                    'Cost':[10000, 5000, 15000, 2000, 12000]})
 
 
# Let's create the index
index_ = [pd.Period('02-2018'), pd.Period('04-2018'),
          pd.Period('06-2018'), pd.Period('10-2018'), pd.Period('12-2018')]
 
# Set the index
df.index = index_
 
# Let's print the dataframe
print(df)


Output :

                      City        Event   Cost
2018-02 New York (City) Music 10000
2018-04 Parague Poetry 5000
2018-06 New Delhi (Delhi) Theatre 15000
2018-10 Venice Comedy 2000
2018-12 new Orleans Tech_Summit 12000

Now we will write our own customized function to match the description in the names of the cities.

Python3




# Importing re package for using regular expressions
import re
 
# Function to clean the names
def Clean_names(City_name):
    # Search for opening bracket in the name followed by
    # any characters repeated any number of times
    if re.search('\(.*', City_name):
 
        # Extract the position of beginning of pattern
        pos = re.search('\(.*', City_name).start()
 
        # return the cleaned name
        return City_name[:pos]
 
    else:
        # if clean up needed return the same name
        return City_name
         
# Updated the city columns
df['City'] = df['City'].apply(Clean_names)
 
# Print the updated dataframe
print(df)


Output :

                City        Event   Cost
2018-02 New York Music 10000
2018-04 Parague Poetry 5000
2018-06 New Delhi Theatre 15000
2018-10 Venice Comedy 2000
2018-12 new Orleans Tech_Summit 12000


Previous Article
Next Article

Similar Reads

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 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
5 min read
How to Remove repetitive characters from words of the given Pandas DataFrame using Regex?
Prerequisite: Regular Expression in Python In this article, we will see how to remove continuously repeating characters from the words of the given column of the given Pandas Dataframe using Regex. Here, we are actually looking for continuously occurring repetitively coming characters for that we have created a pattern that contains this regular ex
2 min read
Split a String into columns using regex in pandas DataFrame
Given some mixed data containing multiple values as a string, let's see how can we divide the strings using regex and make multiple columns in Pandas DataFrame. Method #1: In this method we will use re.search(pattern, string, flags=0). Here pattern refers to the pattern that we want to search. It takes in a string with the following values: \w matc
3 min read
Extract date from a specified column of a given Pandas DataFrame using Regex
In this article, we will discuss how to extract only valid date from a specified column of a given Data Frame. The extracted date from the specified column should be in the form of 'mm-dd-yyyy'. Approach: In this article, we have used a regular expression to extract valid date from the specified column of the data frame. Here we used \b(1[0-2]|0[1-
2 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 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 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.  Methods to Replace NaN V
5 min read
Mapping external values to dataframe values in Pandas
Mapping external values to a dataframe means using different sets of values to add to that dataframe by keeping the keys of the external dictionary as same as the one column of that dataframe. To add external values to dataframe, we use a dictionary that has keys and values which we want to add to the dataframe. By adding external values in the dat
3 min read
Highlight the negative values red and positive values black in Pandas Dataframe
Let's see various methods to Highlight the positive values red and negative values black in Pandas Dataframe.First, Let's make a Dataframe: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], '
3 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
Extract punctuation from the specified column of Dataframe using Regex
Prerequisite: Regular Expression in Python In this article, we will see how to extract punctuation used in the specified column of the Dataframe using Regex. Firstly, we are making regular expression that contains all the punctuation: [!"\$%&\'()*+,\-.\/:;=#@?\[\\\]^_`{|}~]* Then we are passing each row of specific column to re.findall() functi
2 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 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
Python | Pandas dataframe.replace()
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 SyntaxSyntax: DataFrame.replace(to_replace=None, value=None, inplace=False
5 min read
Python Regex: Replace Captured Groups
Regular Expressions, often abbreviated as Regex, are sequences of characters that form search patterns. They are powerful tools used in programming and text processing to search, match, and manipulate strings. Think of them as advanced search filters that allow us to find specific patterns within a text, such as email addresses, dates, phone number
5 min read
Using dictionary to remap values in Pandas DataFrame columns
While working with data in Pandas in Python, we perform a vast array of operations on the data to get the data in the desired form. One of these operations could be that we want to remap the values of a specific column in the DataFrame. Let's discuss several ways in which we can do that. Creating Pandas DataFrame to remap valuesGiven a Dataframe co
3 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
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
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 and makes importing and analyzing data much easier.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
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, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Replace the column contains the values 'yes' and 'no' with True and False In Python-Pandas
Let’s discuss a program To change the values from a column that contains the values 'YES' and 'NO' with TRUE and FALSE. First, Let's see a dataset. Code: C/C++ Code # import pandas library import pandas as pd # load csv file df = pd.read_csv("supermarkets.csv") # show the dataframe df Output : For downloading the used csv file Click Here.
2 min read
How to Replace Values in Column Based on Condition in Pandas?
In Python using Pandas, values in a DataFrame column can be replaced based on conditions by utilizing various built-in functions. In this article, we are going to discuss the various methods to replace the values in the columns of a dataset in Pandas with conditions. Replace Values in Column Based on Condition in PandasBelow are the methods by whic
6 min read
Pandas Replace Multiple Values in Python
Replacing multiple values in a Pandas DataFrame or Series is a common operation in data manipulation tasks. Pandas provides several versatile methods for achieving this, allowing you to seamlessly replace specific values with desired alternatives. In this context, we will explore various approaches to replace multiple values in Python using Pandas.
5 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
three90RightbarBannerImg