pandas 中的 DataFrame.ix() - 当请求的列不存在时,是否有选项可以捕获情况?

DataFrame.ix() in pandas - is there an option to catch situations when requested columns do not exist?

提问人:Lev Selector 提问时间:6/7/2012 最后编辑:piRSquaredLev Selector 更新时间:1/5/2017 访问量:4367

问:

我的代码将 CSV 文件读取到 pandas 中 - 并对其进行处理。 代码依赖于列名 - 使用 df.ix[,] 获取列。 最近,CSV 文件中的某些列名称已更改(恕不另行通知)。 但代码并没有抱怨,而是默默地产生了错误的结果。 ix[,] 构造不检查列是否存在。 如果没有 - 它只是创建它并用 NaN 填充。 这是正在发生的事情的主要思想。DataFrame

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)
数据帧 熊猫

评论


答:

0赞 Jon Clements 6/10/2012 #1

不确定是否可以约束 DataFrame,但您的帮助程序函数可以简单得多。(类似的东西)

mismatch = set(cols).difference(set(dfcols))
    if mismatch:
        raise SystemExit('Unknown column(s): {}'.format(','.join(mismatch)))
3赞 Wes McKinney 6/13/2012 #2

怎么样:

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]'