How to select all columns whose name start with a particular string in pandas DataFrame?

Given a Pandas DataFrame, we have to select all columns whose name start with a particular string.
Submitted by Pranit Sharma, on June 19, 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.

Select all columns whose name start with a particular string

To select all columns whose name starts with a particular string in pandas DataFrame, we will select all the columns whose name starts with a particular string and store all these columns in a list. This can be done by using a comprehension statement inside a list and checking if a column name starts with a specific string or not.

We will use the startswith() method to check if the name of the column starts with a specific string or not. If True, it will be stored in a list otherwise not. Finally, we will select the DataFrame with these particular columns.

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,

Python program to select all columns whose name start with a particular string

# Importing pandas package
import pandas as pd

# Create d DataFrame
df = pd.DataFrame({
    'boy.name':['Pranit','Sudhir','Raman','Jatin'],
    'girl.name':['Apurva','Deepti','Richa','Sheetal'],
    'boy.age':[20,30,34,28],
    'girl.age':[20,23,19,39]
})

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

# Filtering DataFrame where column start with 'boy'
result = [i for i in df if i.startswith('boy')]

# Display result
print("Filtered Data:\n",df[result])

Output

Example: Select all columns

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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