How to Check if Column Exists in Pandas
Published on Aug. 22, 2023, 12:16 p.m.
To check if a column exists in a Pandas DataFrame, you can use the “in” expression with the df.columns
attribute. Here’s an example:
import pandas as pd
# create a DataFrame
df = pd.DataFrame({'column1': [1, 2, 3], 'column2': [4, 5, 6]})
# check if 'column1' exists in the DataFrame
if 'column1' in df.columns:
print('column1 exists')
else:
print('column1 does not exist')
Output:
column1 exists
You can also check if multiple columns exist by passing a list of column names to the “in” expression. For example:
import pandas as pd
# create a DataFrame
df = pd.DataFrame({'column1': [1, 2, 3], 'column2': [4, 5, 6]})
# check if 'column1' and 'column2' exist in the DataFrame
if all(col in df.columns for col in ['column1', 'column2']):
print('All columns exist')
else:
print('At least one column does not exist')
Output:
All columns exist
I hope this helps! Let me know if you have any other questions.