How to Check If a Column Exist in Pandas?

Spread the love

Problem –

You want to know whether or not a column exist in a pandas dataframe.

Solution –

Let’s read a dataset to explain it.

import pandas as pd

url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv'
df = pd.read_csv(url)
df.head()

Now, If I want to check whether the Age column exist or not in the dataframe, I can use

if 'Age' in df.columns:
    print("Yes, It Exist!")
else:
    print("NO, It's Not!")

output - Yes, It Exist!

Let’s check a column that does not exist in the dataframe.

if 'Price' in df.columns:
    print("Yes, It Exist!")
else:
    print("NO, It's Not!")

output - NO, It's Not!

Rating: 1 out of 5.

Leave a Reply