Python - Replace all occurrences of a string in a pandas dataframe

Learn, how can we replace all occurrences of a string in a pandas dataframe with example? By Pranit Sharma Last updated : September 26, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

When it comes to replacing a string, it means assigning some new string in place of the original string.

Problem statement

Let's suppose, we have a Pandas DataFrame which consists of two columns, we need to replace all occurrences of some string from the columns of this DataFrame.

Replacing all occurrences of a string in a pandas dataframe

For this purpose, we will use df.replace() method. We will pass a parameter called regex=True inside this function.

Let us understand with the help of an example,

Python program to replace all occurrences of a string in a pandas dataframe

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'a': ['1*', '2*', '3'], 
    'b': ['4*', '5*', '6*']
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame :\n",df,"\n")

# Replacing all occurrences of * in DataFrame
for col in df.columns:
   df[col] = df[col].str.replace('*', '#')

# display modified DataFrame
print("Result:\n",df)

Output

The output of the above program is:

Example: Replace all occurrences of a string

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.