How to check if a column exists in Pandas

前端 未结 3 1893
伪装坚强ぢ
伪装坚强ぢ 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: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.

提交回复
热议问题