【问题标题】:if else on dataframe header giving KeyErrorif else on dataframe header给出KeyError
【发布时间】:2020-10-08 09:18:31
【问题描述】:

我有一些数据文件,用户通过 gui 从中选择,以确定他们需要哪些预处理列标题或 cmets 字段中的内容。

包含“评论”标题的文件数据

以下适用于具有 cmets 字段的文件。当我用它来测试一个没有 cmets 字段的 texfile 时,我得到了一个例外——在我看来,当这种情况发生时它应该只运行“else”主体。

代码

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'

【问题讨论】:

    标签: python pandas dataframe if-statement logic


    【解决方案1】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      相关资源
      最近更新 更多