从Excel载入资料时,Python _getitem_和_getitem_column(key)错误

时间:2019-09-19 17:45:40

标签: pandas error-handling

我有一个数据框,其中有20张不同的图纸。它通常在前16张纸上运行,但在第17张纸上出现错误。这是我的代码:

A=A.sort_values(by=['timing','id'])

错误是:

Traceback (most recent call last):

  File "<ipython-input-24-11bf4f35bb1b>", line 1, in <module>
    SessionNumber(5)

  File "filepath", line 160
    DepthBuyA=DepthBuyA.sort_values(by=['timing','id'])

  File "C:\Anaconda\lib\site-packages\pandas\core\frame.py", line 4411, in sort_values
    stacklevel=stacklevel)

  File "C:\Anaconda\lib\site-packages\pandas\core\generic.py", line 1382, in _get_label_or_level_values
    raise KeyError(key)

KeyError: 'id'

所以我认为,该特定工作表上的“ id”列一定存在一些问题,因为其他工作表也具有“ id”,并且没有一个出现这样的错误。所以我尝试了:

print(A['id'])

它成功打印了工作表17的'id'列,但是,在打印完它后,立即出现此错误:

  File "C:\Anaconda\lib\site-packages\pandas\core\frame.py", line 2688, in __getitem__
    return self._getitem_column(key)

  File "C:\Anaconda\lib\site-packages\pandas\core\frame.py", line 2695, in _getitem_column
    return self._get_item_cache(key)

  File "C:\Anaconda\lib\site-packages\pandas\core\generic.py", line 2489, in _get_item_cache
    values = self._data.get(item)

  File "C:\Anaconda\lib\site-packages\pandas\core\internals.py", line 4115, in get
    loc = self.items.get_loc(item)

  File "C:\Anaconda\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas\_libs\index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'id'

因此,在此之后,我尝试将代码直接放入控制台,现在没有错误。

A=A.sort_values(by=['timing','id'])

那是什么问题,我该怎么解决? 谢谢!

1 个答案:

答案 0 :(得分:1)

使用列索引代替名称,现在可以了