How to check if a column exists in Pandas

Question

How do I check if a column exists in a Pandas DataFrame df?

   A   B    C
0  3  40  100
1  6  30  200

How would I check if the column "A" exists in the above DataFrame so that I can compute:

df['sum'] = df['A'] + df['C']

And if "A" doesn't exist:

df['sum'] = df['B'] + df['C']

Answer

This will work:

if 'A' in df:

But for clarity, I'd probably write it as:

if 'A' in df.columns:

How do I get the row count of a Pandas DataFrame?

How to avoid pandas creating an index in a saved csv