Check whether a given column is present in a Dataframe

In Pandas DataFrame, the DataFrame.columns attribute returns the column labels of the given DataFrame. To check if a column exists in a Pandas DataFrame, you can use the "in" expression along with the column name you want to check. For example, you can use the expression "column_name in df.columns" to determine if the column with the specified name exists in the DataFrame or not. If the column exists, it will return True; otherwise, it will return False.

import pandas as pd import numpy as np df = pd.DataFrame() df['Name'] = ['John', 'Doe', 'Bill'] df['Promoted'] = [True, False,True] df['Marks'] = [82, 38, 63] df
Name Promoted Marks 0 John True 82 1 Doe False 38 2 Bill True 63

Use in

To check whether a given column is present in a Pandas DataFrame, you can use the "in" expression along with the DataFrame.columns attribute.

if 'Promoted' in df.columns: print("Yes") else: print("No")
Yes

Use not in

To check whether a given column is not present in a Pandas DataFrame, you can use the "not in" expression along with the DataFrame.columns attribute.

if 'Promoted' not in df.columns: print("Yes") else: print("No")
No

Check for multiple columns exists in DataFrame

if set(['Name','Promoted']).issubset(df.columns): print("Yes") else: print("No")
Yes

How to Check whether a given column is present in a Dataframe

You can alternatively be constructed with curly braces {}.

if not {'Name', 'Promoted'}.issubset(df.columns): print("Yes") else: print("No")
No

Conclusion

To check whether a given column is present in a Pandas DataFrame, you can use the "in" expression along with the DataFrame.columns attribute. If the column is present, the expression will evaluate to True; otherwise, it will be False. Alternatively, you can use the "not in" expression to check if the column is not present in the DataFrame.