if else on dataframe header 给出 KeyError

if else on dataframe header giving KeyError

我有一些数据文件,用户可以通过 gui 从中选择,以确定他们需要哪个 pre-processing 我有一个 if-else(以下示例已简化但会产生回溯)来测试哪种类型数据文件的列 headers 或注释字段中的内容。

包含“评论”的文件的数据header

以下内容适用于 具有 注释字段的文件。当我用它来测试一个没有注释字段的 texfile 时,我得到一个异常 - 我的想法应该是 运行 'else' body 当发生这种情况时。

代码

if df["Comments"].str.contains("Sclk" or "segs").any():
    print("this might be OPW data")
else:
    print('NOT opw data')

回溯

Traceback (most recent call last):
  File "/Users/.../Desktop/tk_gui_grid/get_data_01.py", line 47, in <module>
    if df["Comments"].str.contains("Sclk" or "segs").any():
  File "/Users/.../opt/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/Users/.../opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1618, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1626, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Comments'

试试这个:

if 'Comments' in df.columns and df[df["Comments"].isin(['Sclk', 'segs'])].shape[0] != 0:
    print("this might be OPW data")
else:
    print('NOT opw data')