How to check if a column exists in Pandas

前端 未结 3 1866
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 18:33

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
>&         


        
相关标签:
3条回答
  • 2020-11-28 18:44

    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']]):
    
    0 讨论(0)
  • 2020-11-28 18:49

    Just to suggest another way without using if statements, you can use the get() method for DataFrames. 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.

    0 讨论(0)
  • 2020-11-28 18:53

    This will work:

    if 'A' in df:
    

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

    if 'A' in df.columns:
    
    0 讨论(0)
提交回复
热议问题