Replace part of the string in pandas dataframe

Given a pandas dataframe, we have to replace part of the string in pandas dataframe. By Pranit Sharma Last updated : October 05, 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.

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.

Problem statement

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 part of the string

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 program 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)


The output of the above program is:

Example: Replace part of the string in pandas dataframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.