私のコードは、CSV ファイルを pandas に読み込みDataFrame
、処理します。コードは列名に依存しています - df.ix[,] を使用して列を取得します。最近、CSV ファイルの一部の列名が (予告なく) 変更されました。しかし、コードは文句を言うのではなく、黙って間違った結果を生成していました。ix[,] コンストラクトは、列が存在するかどうかをチェックしません。そうでない場合は、単純に作成して NaN を入力します。これが何が起こっていたかの主なアイデアです。
df1=DataFrame({'a':[1,2,3],'b':[4,5,6]}) # columns 'a' & 'b'
df2=df1.ix[:,['a','c']] # trying to get 'a' & 'c'
print df2
a c
0 1 NaN
1 2 NaN
2 3 NaN
したがって、エラーや警告は生成されません。
列が存在することを追加チェックして特定の列を選択する別の方法はありますか?
私の現在の回避策は、次のような独自の小さなユーティリティ関数を使用することです。
import sys, inspect
def validate_cols_or_exit(df,cols):
"""
Exits with error message if pandas DataFrame object df
doesn't have all columns from the provided list of columns
Example of usage:
validate_cols_or_exit(mydf,['col1','col2'])
"""
dfcols = list(df.columns)
valid_flag = True
for c in cols:
if c not in dfcols:
print "Error, non-existent DataFrame column found - ",c
valid_flag = False
if not valid_flag:
print "Error, non-existent DataFrame column(s) found in function ", inspect.stack()[1][3]
print "valid column names are:"
print "\n".join(df.columns)
sys.exit(1)