python
[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")
else:
print("Column does not exist in the DataFrame")
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?
Similar Posts
- [Pandas] Add new column to DataFrame based on existing column
- Change column orders using column names list - Pandas Dataframe
- Pandas - Delete,Remove,Drop, column from pandas DataFrame
- Check if a column contains zero values only in Pandas DataFrame
- Pandas - How to check whether a pandas DataFrame is empty
- Reorder dataframe columns using column names in pandas
- Get a value from DataFrame row using index and column name in pandas