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 回答
0

不确定您是否可以约束 DataFrame,但您的辅助函数可能要简单得多。(就像是)

mismatch = set(cols).difference(set(dfcols))
    if mismatch:
        raise SystemExit('Unknown column(s): {}'.format(','.join(mismatch)))
于 2012-06-09T17:33:57.327 回答