Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Exclude Columns in Pandas?

Improve Article
Save Article
  • Last Updated : 15 Sep, 2022
Improve Article
Save Article

In this article, we will discuss how to exclude columns in pandas dataframe.

Creating the DataFrame

Here we are creating the dataframe using pandas library in Python.

Python3




# import pandas module
import pandas as pd
 
# create food dataframe
data = pd.DataFrame({'food_id': [1, 2, 3, 4],
                     'name': ['idly', 'dosa', 'poori', 'chapathi'],
                     'city': ['delhi', 'goa', 'hyd', 'chennai'],
                     'cost': [12, 34, 21, 23]})
 
# display
data


Output:

How to Exclude Columns

How to Exclude Columns

Exclude One Column using dataframe.loc

We can exclude one column from the pandas dataframe by using the loc function. This function removes the column based on the location.

Syntax: dataframe.loc[ : , ddataframe.columns!=’column_name’]

Here we will be using the loc() function with the given data frame to exclude columns with name,city, and cost in python.

Python3




# exclude name column
print(data.loc[:, data.columns != 'name'])
 
# exclude city column
print(data.loc[:, data.columns != 'city'])
 
# exclude cost column
print(data.loc[:, data.columns != 'cost'])


Output:

How to Exclude Columns

How to Exclude Columns

Exclude Multiple columns using dataframe.loc

Here we are using loc function with isin operator to exclude the multiple columns

Syntax:

dataframe.loc[:, ~dataframe.columns.isin([‘column1’,………………, ‘column n’])]

Example:

In this example, we will be using the isin operator to exclude the name and food_id column from the given data frame.

Python3




# exclude name and food_id column
print(data.loc[:, ~data.columns.isin(['name', 'food_id'])])


Output:

How to Exclude Columns

How to Exclude Columns

Removing the column from the dataframe

Here we are excluding the column from the dataframe by fetching all the columns and removing the desired one and printing the modified dataframe.

Python3




# printing the original dataframe
print(df)
 
# getting all the columns
my_cols = set(df.columns)
 
# removing the desired column
my_cols.remove('city')
 
my_cols = list(my_cols)
df2 = df[my_cols]
 
# printing the modified dataframe
print(df2)


Output:

How to Exclude Columns

How to Exclude Columns

For more ways you can refer to this article:

https://www.geeksforgeeks.org/how-to-drop-one-or-multiple-columns-in-pandas-dataframe/


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!