Check whether a given column is present in a Pandas DataFrame or not
Consider a Dataframe with 4 columns : ‘ConsumerId’, ‘CarName’, CompanyName, and ‘Price’. We have to determine whether a particular column is present in the DataFrame or not in Pandas Dataframe using Python.
Creating a Dataframe to check if a column exists in Dataframe
Python3
import pandas as pd
d = { 'ConsumerId' : [ 1 , 2 , 3 ,
4 , 5 ],
'CarName' : [ 'I3' , 'S4' , 'J3' ,
'Mini' , 'Beetle' ],
'CompanyName' : [ 'BMW' , 'Mercedes' , 'Jeep' ,
'MiniCooper' , 'Volkswagen' ],
'Price' : [ 1200 , 1400 , 1500 ,
1650 , 1750 ]
}
df = pd.DataFrame(d)
df
|
Output:
Check if Column Exists in Pandas using in keyword
To check whether the ‘ConsumerId’ column exists in Dataframe or not using Python in keyword.
Python
if 'ConsumerId' in df.columns :
print ( 'ConsumerId column is present' )
else :
print ( 'ConsumerId column is not present' )
|
Output:
ConsumerId column is present
Check if Column Exists in Pandas using issubset()
To check whether the ‘CarName’ and ‘Price’ columns exist in Dataframe or not using issubset() function.
Python
{ 'Price' , 'CarName' }.issubset(df.columns)
|
Output:
True
Check if Column Exists in Pandas using all() function
To check whether the ‘Fuel’ column exists in Dataframe or not using all() function.
Python
all (item in df.columns for item in [ 'Fuel' ])
|
Output:
False
Last Updated :
27 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...