You can also call isin()
on the columns to check if specific column(s) exist in it and call any()
on the result to reduce it to a single boolean value1. For example, to check if a dataframe contains columns A
or C
, one could do:
if df.columns.isin(['A', 'C']).any():
# do something
To check if a column name is not present, you can use the not
operator in the if-clause:
if 'A' not in df:
# do something
or along with the isin().any()
call.
if not df.columns.isin(['A', 'C']).any():
# do something
1: isin()
call on the columns returns a boolean array whose values are True if it's either A
or C
and False otherwise. The truth value of an array is ambiguous, so any()
call reduces it to a single True/False value.