Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 29 Jul, 2021

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 this pandas program, we are using Dataframe.columns attribute That return the column labels of the given Dataframe.

Syntax: Dataframe.columns

Parameter: None

Returns: column names

Let’s create a Dataframe:
Code: 

Python




# 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: 

dataframe

Example 1: To check whether the ‘ConsumerId’ column exists in Dataframe or not. 

Python




if 'ConsumerId' in df.columns :
  print('ConsumerId column is present')
    
else:
  print('ConsumerId column is not present')

 
 Output:  

ConsumerId column is present

Example 2: To check whether the ‘CarName’ column exists in Dataframe or not.

Python




if 'CarName' in df.columns:
  print('CarName column is present')
    
else:
  print('CarName column is not present')

 Output:  

CarName column is present

 Example 3: To check whether the ‘CarType’ column exists in Dataframe or not. 

Python




if 'CarType' in df.columns:
  print('CarType column is present')
    
else:
  print('CarType column is not present')

Output: 

CarType column is not present

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!