How to check if a column exists in Pandas
You can use the set's method issuperset
:
set(df).issuperset(['A', 'B'])
# set(df.columns).issuperset(['A', 'B'])
Just to suggest another way without using if statements, you can use the get()
method for DataFrame
s. For performing the sum based on the question:
df['sum'] = df.get('A', df['B']) + df['C']
The DataFrame
get method has similar behavior as python dictionaries.
This will work:
if 'A' in df:
But for clarity, I'd probably write it as:
if 'A' in df.columns:
To check if one or more columns all exist, you can use set.issubset
, as in:
if set(['A','C']).issubset(df.columns):
df['sum'] = df['A'] + df['C']
As @brianpck points out in a comment, set([])
can alternatively be constructed with curly braces,
if {'A', 'C'}.issubset(df.columns):
See this question for a discussion of the curly-braces syntax.
Or, you can use a generator comprehension, as in:
if all(item in df.columns for item in ['A','C']):