Open In App

Check whether a given column is present in a Pandas DataFrame or not

Improve
Improve
Like Article
Like
Save
Share
Report

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 library
import pandas as pd
 
# dictionary
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]
    }
 
# create a dataframe
df = pd.DataFrame(d)
 
# show the dataframe
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




# Syntax
# {'ColumnName'}.issubset(df.columns)
 
{'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
Previous
Next
Share your thoughts in the comments
Similar Reads