Selecting/excluding sets of columns in pandas

Learn how to select/exclude sets of columns in pandas?
Submitted by Pranit Sharma, on May 04, 2022

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Suppose we want to display all the columns except some specified columns, DataFrame.loc() helps us to achieve this task.


DataFrame.loc[:, df.columns!= 'column_name']

Here, the DataFrame.loc() property will read the sliced index, colon (:) means starting from the first column, DataFrame.columns will return all the columns of a DataFrame and define a specified column name after the conditional operator (!=) will return all the column names except the one which is specified inside the method.

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

# Creating a dictionary
d = {
    'Roll_no': [ 1,2,3,4,5],
    'Name': ['Abhishek', 'Babita','Chetan','Dheeraj','Ekta'],
    'Gender': ['Male','Female','Male','Male','Female'],
    'Marks': [50,66,76,45,80],
    'Standard': ['Fifth','Fourth','Third','Third','Third']

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

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


Output 1: Selecting sets of columns

Now, we will print the DataFrame by excluding some columns

# 1] Display columns according to our requirements


Output 1:

Output 2: Selecting sets of columns
# 2] Display columns according to our requirements


Output 2:

Output 3: Selecting sets of columns
# 3] Display columns according to our requirements


Output 3:

Output 4: Selecting sets of columns

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.