Replace whole string if it contains substring in pandas

Given a pandas dataframe, we have to replace whole string if it contains substring in it.
Submitted by Pranit Sharma, on September 14, 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.

Pandas - Replacing whole string if it contains substring

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.

Suppose, we have a DataFrame that contains a string-type column and we need to filter the column based on a substring, if the value contains that particular substring, we need to replace the whole string.

Let us understand with the help of an example,

Python code to replace whole string if it contains substring in pandas

# Importing pandas package
import pandas as pd

# Creating a dictionary with equal elements
d = {

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

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

# Filtering and replacing Stream column
df.loc[df['stream'].str.contains('aths'), 'stream'] = 'Arts'

# Display modified DataFrame
print("Modified DataFrame:\n",df)


Example: Replace whole string if it contains substring

Python Pandas Programs »


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

© some rights reserved.