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
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.