ADVERTISEMENT
ADVERTISEMENT

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.

Filtering is a process of selecting some sort of information according to our specific demands. Filtering in pandas is important for learning about the properties of specific elements and hence results in effective data analysis.

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 code 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 »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.