Search code snippets, questions, articles...

[Pandas] Check if a column exists in a DataFrame

We will learn in this post to check if a column exists in a Pandas DataFrame or not. We will write the condition to return true if the column exists and return false if the column does not exist.
import pandas as pd

employees = [
  ['Robin', 30, 'SOS', 'India'],
  ['Rick', 28, 'PSA', 'US'],
  ['Tony Stark', 32, 'COS', 'US']

# create dataframe
df = pd.DataFrame(employees, columns=['Name', 'Age', 'Dept', 'Country'])

# check if column exist in the dataframe
if 'Age' in df.columns:
  print("Coumn exists in the DataFrame")
  print("Column does not exist in the DataFrame")
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

If you want to check whether a column exists in a Pandas DataFrame or not then you can use the methods explained in this post.

We are using the "in" keyword to check that. Below is the example to understand it..

"column_name" in df

Or we can use

"column_name" in df.columns
Was this helpful?