4

私のコードは、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)
4

2 に答える 2

3

どうですか:

In [3]: df1[['a', 'c']]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/home/wesm/code/pandas/<ipython-input-3-2349e89f1bb5> in <module>()
----> 1 df1[['a', 'c']]

/home/wesm/code/pandas/pandas/core/frame.py in __getitem__(self, key)
   1582             if com._is_bool_indexer(key):
   1583                 key = np.asarray(key, dtype=bool)
-> 1584             return self._getitem_array(key)
   1585         elif isinstance(self.columns, MultiIndex):
   1586             return self._getitem_multilevel(key)

/home/wesm/code/pandas/pandas/core/frame.py in _getitem_array(self, key)
   1609             mask = indexer == -1
   1610             if mask.any():
-> 1611                 raise KeyError("No column(s) named: %s" % str(key[mask]))
   1612             result = self.reindex(columns=key)
   1613             if result.columns.name is None:

KeyError: 'No column(s) named: [c]'
于 2012-06-12T21:20:16.703 に答える