Is there a way to check if a column exists in a Pandas DataFrame?
Suppose that I have the following DataFrame:
>>> import pandas as pd
>&
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 list comprehension, as in:
if all([item in df.columns for item in ['A','C']]):
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: