Replace part of the string in pandas dataframe

Given a pandas dataframe, we have to replace part of the string in pandas dataframe.
Submitted by Pranit Sharma, on November 21, 2022

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.

Replacing part of the string

Suppose we are given a dataframe whose columns have string values. We need to find a way so we can replace some part of the string value with some other string.

Replacing some part of a string is like replacing a substring of a string, A substring is a sequence of characters within a string that is contiguous. For example, "llo Wor" is a substring of "Hello World". The important point is sequence is different from sub-sequence, "loWor" is a subsequence of "Hello World", but not a substring.

For this purpose, we will simply use the replace method of string inside which will pass a parameter 'rejex=true', and also, we will create a key-value pair of the old value and the new value.

Let us understand with the help of an example

Python code to replace part of the string in pandas dataframe

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating dataframe
df = pd.DataFrame({'Name':['Mr Arpit','Mr Atul','Mr Sanjay','Mr Jayesh','Mr Deepak']})

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

# Replacing s piece of string
res = df.Name.replace({'Mr':'Dr'}, regex=True)

# Display Result
print('New DataFrame:\n',res)

Output:

Example: Replace part of the string in pandas dataframe

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.