How to check if a column exists in Pandas

Is there a way to check if a column exists in a Pandas DataFrame?

Suppose I have the following DataFrame:

>>> import pandas as pd >>> from random import randint >>> df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)], 'B': [randint(1, 9)*10 for x in xrange(10)], 'C': [randint(1, 9)*100 for x in xrange(10)]}) >>> df ABC 0 3 40 100 1 6 30 200 2 7 70 800 3 3 50 200 4 7 50 400 5 4 10 400 6 3 70 500 7 8 30 200 8 3 40 800 9 6 60 200 

and I want to calculate df['sum'] = df['A'] + df['C']

But first I want to check if df['A'] exists, and if not, then instead I want to calculate df['sum'] = df['B'] + df['C'] .

+171
python pandas dataframe
Jul 21 '14 at 16:43
source share
3 answers

This will work:

 if 'A' in df: 

But for clarity, I would probably write this as:

 if 'A' in df.columns: 
+366
Jul 21 '14 at 16:48
source share

To check if one or more columns exist, you can use set.issubset , for example:

 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 using curly braces,

 if {'A', 'C'}.issubset(df.columns): 

See this question for a discussion of the braces syntax.

Or you can use list comprehension, as in:

 if all([item in df.columns for item in ['A','C']]): 
+44
07 Sept. '16 at 13:55 on
source share

To suggest another way without using if statements, you can use the get() method for DataFrame s. To fulfill the amount based on the question:

 df['sum'] = df.get('A', df['B']) + df['C'] 

The DataFrame get method has similar behavior as python dictionaries.

+6
May 22 '17 at 18:28
source share



All Articles