【发布时间】:2019-12-03 21:51:28
【问题描述】:
我意识到这个问题之前已经解释过很多次了,所以我理解这是否作为重复而关闭,但我有一些更理论的问题要问,这可能证明这是一个新问题。我是 Python(和 SO)的新手,所以请耐心等待。
我正在尝试读取一个 .csv 文件,该文件有 16 列和 30,000 行,填充了从 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])
我将在下面发布错误的记录。即使我有一个工作代码,我也尝试这样做的原因是因为当我编写完整的脚本时,我正在迭代已知数量的行。值得一提的是,我在 Jupyter online 上做这个。
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
【问题讨论】:
-
错误的原因是因为您的数据框很可能没有使用整数作为其列名,因此整数 0 到 15 将导致您看到的
KeyError,这是最后一行两个例外:KeyError: 0. -
@b_c 我尝试将列名更改为整数 0 到 15,但我仍然收到此错误。我直接在 .csv 中更改了它们,而不是在我的 Python 代码中。
-
由于您是从 csv 读取数据,因此它们很可能被读取为字符串(即“0”、“1”,而不仅仅是 0、1 等)
标签: python pandas numpy dataframe compiler-errors