Drop columns whose name contains a specific string from pandas DataFrame

Given a Pandas DataFrame, we have to drop columns whose name contains a specific string.
Submitted by Pranit Sharma, on June 11, 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 the data. The Data inside the DataFrame can be of any type.

To drop a column that contains some specific string, we will use the regex pattern.

Regex (Regular Expression):

A special format string is used for searching and filtering in pandas DataFrame rows.


  • 'K.*' : It will filter all the records which start with the letter 'K'.
  • 'A.*' : It will filter all the records which start with the letter 'A'.

We will compare if the DataFrame consists of our specific regex or not, if yes, we will drop that particular column.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

# Importing pandas package
import pandas as pd

# Defining two DataFrames
df = pd.DataFrame(data = {
    'Dabur':['Chawanprash','Honey','Hair oil','Hajmola']

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

# Dropping a column which consists a string 'Dabur'
result = df[df.columns.drop(list(df.filter(regex='Dabur')))]

# Display result
print("DataFrame after dropping the column which contains 'Dabur':\n",result)


Example: Drop columns

Python Pandas Programs »


What's New (MCQs)

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.