有没有一种方法可以检查Pandas DataFrame中是否存在列?
假设我有以下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 A B C 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
我想计算 df['sum'] = df['A'] + df['C']
df['sum'] = df['A'] + df['C']
但是首先我要检查是否df['A']存在,如果不存在,我要计算df['sum'] = df['B'] + df['C']。
df['A']
df['sum'] = df['B'] + df['C']
这将起作用:
if 'A' in df:
但是为了清楚起见,我可能将其写为:
if 'A' in df.columns: