pythonpandasdataframemembershipany

How to check if a column exists in Pandas


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']

Solution

  • This will work:

    if 'A' in df:
    

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

    if 'A' in df.columns: