How to Exclude Columns in Pandas?
Last Updated :
31 Jul, 2023
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 as pd
data = pd.DataFrame({ 'food_id' : [ 1 , 2 , 3 , 4 ],
'name' : [ 'idly' , 'dosa' , 'poori' , 'chapathi' ],
'city' : [ 'delhi' , 'goa' , 'hyd' , 'chennai' ],
'cost' : [ 12 , 34 , 21 , 23 ]})
data
|
Output:
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[ : , dataframe.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
print (data.loc[:, data.columns ! = 'name' ])
print (data.loc[:, data.columns ! = 'city' ])
print (data.loc[:, data.columns ! = 'cost' ])
|
Output:
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
print (data.loc[:, ~data.columns.isin([ 'name' , 'food_id' ])])
|
Output:
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
print (df)
my_cols = set (df.columns)
my_cols.remove( 'city' )
my_cols = list (my_cols)
df2 = df[my_cols]
print (df2)
|
Output:
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/
Share your thoughts in the comments
Please Login to comment...