python - 解释 “Traceback (most recent call last):”错误

标签 python pandas numpy dataframe compiler-errors

我意识到这个问题已经被解释过很多次了,所以我知道它是否可以重复出现,但是我还有其他一些理论性问题可以提出来作为一个新问题。我是Python(和SO)的新手,所以请耐心等待。

我正在尝试读取具有16列和30,000ish行的.csv文件,该文件填充了0到17之间的值。没有空单元格。我想做的是遍历每一行,并对每行中的单元格进行逐项减法。目前,我正在尝试使用Pandas DataFrame进行此操作。所以我的第一个问题是:我应该使用其他数据结构吗?我读过DataFrame不利于遍历行。

接下来,对于标题问题,我需要帮助解释我的错误。到目前为止,我只编写了代码来尝试对一小部分数据进行这种减法。这是我的代码:

import numpy as np
import pandas as pd
scrambles = pd.read_csv('scrambles.csv')
df = pd.DataFrame(scrambles)
#print(df)
columns = list(df)
for i in columns:
    print (df[i][0]-df[i][1])

这一切都按预期进行。但是,当我将最后一段代码更改为以下代码时,出现错误:
for i in range(15):
    print (df[i][0]-df[i][1])

我将在下面发布错误的笔录。即使我有一个有效的代码,我也尝试这样做的原因是因为当我编写完整的脚本时,我要遍历已知数量的行。对于它的值(value),我正在Jupyter在线上进行。


KeyError                                  Traceback (most recent call last)
/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2889             try:
-> 2890                 return self._engine.get_loc(key)
   2891             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-6-0faa876fbe56> in <module>
      1 for i in range(15):
----> 2     print (df[i][0]-df[i][1])

/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key)
   2973             if self.columns.nlevels > 1:
   2974                 return self._getitem_multilevel(key)
-> 2975             indexer = self.columns.get_loc(key)
   2976             if is_integer(indexer):
   2977                 indexer = [indexer]

/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2890                 return self._engine.get_loc(key)
   2891             except KeyError:
-> 2892                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2893         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2894         if indexer.ndim > 1 or indexer.size > 1:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

最佳答案

我将在评论中扩展回答原始问题-解释异常。

The cause for the error is because your dataframe most likely is not using integers for its column names, so the integers 0 through 15 will cause the KeyError you're seeing, which is the final line of both Exceptions: KeyError: 0



在Traceback中,Python为您提供了正在发生的错误的其他上下文。

当您尝试访问数据框的0列时,处理代码将到达base.py函数中get_loc()的第2890行。

在该代码中,出现的KeyError由包含的try/except处理。但是,该处理调用还会引发一个未被处理的KeyError(不幸的是,该调用也未包含在Traceback中)。这是“During handling of the above exception, another exception occurred:”消息进入的地方。

为了说明使用代码本身:
            ...
            try:
                return self._engine.get_loc(key) # <- KeyError raised here
            except KeyError:                     # <- Caught by except
                return self._engine.get_loc(self._maybe_cast_indexer(key)) # <- 2nd KeyError
            ...

最后,正如我在评论中所说,Traceback的最后一行揭示了错误:
KeyError: 0

关于python - 解释 “Traceback (most recent call last):”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59165907/

相关文章:

python - Pandas DataFrame 列的 boolean 掩码

python - 如何将CNN应用于短时傅立叶变换?

python - python中的关联组

python - 应用 pandas df 中所有列的分布

python - None 和 <无值> 之间的区别

python - 附加到 for 循环内的 numpy 数组或列表 - 哪个更可取?

python - 缺少数据的python中的二维卷积

python - Pydoc 没有看到文档字符串?

python - Pandas - 在时间桶中对行进行分组

python pandas pivot_table 列一级错误名称