我正在阅读《Hands on machine Learning with scikit-learn》一书来学习机器学习,下面是显示 MNIST 图像的代码,但当我keyError 0尝试从数据集中索引单个图像时,我得到了 。
from sklearn.datasets import fetch_openml
mnist = fetch_openml('mnist_784', version=1)
X, y = mnist["data"], mnist["target"]
some_digit = X[0]
Run Code Online (Sandbox Code Playgroud)
以下是在 jupyter 笔记本中运行单元时出现的错误。
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
File ~\anaconda3\anaconda-py\envs\data-science\lib\site-packages\pandas\core\indexes\base.py:3621, in Index.get_loc(self, key, method, tolerance)
3620 try:
-> 3621 return self._engine.get_loc(casted_key)
3622 except KeyError as err:
File ~\anaconda3\anaconda-py\envs\data-science\lib\site-packages\pandas\_libs\index.pyx:136, in pandas._libs.index.IndexEngine.get_loc()
File ~\anaconda3\anaconda-py\envs\data-science\lib\site-packages\pandas\_libs\index.pyx:163, in pandas._libs.index.IndexEngine.get_loc()
File pandas\_libs\hashtable_class_helper.pxi:5198, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas\_libs\hashtable_class_helper.pxi:5206, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 0
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Input In [10], in <cell line: 3>()
1 import matplotlib as mpl
2 import matplotlib.pyplot as plt
----> 3 some_digit = X[0]
4 some_digit_image = some_digit.reshape(28, 28)
5 plt.imshow(some_digit_image, cmap = mpl.cm.binary, interpolation="nearest")
File ~\anaconda3\anaconda-py\envs\data-science\lib\site-packages\pandas\core\frame.py:3505, in DataFrame.__getitem__(self, key)
3503 if self.columns.nlevels > 1:
3504 return self._getitem_multilevel(key)
-> 3505 indexer = self.columns.get_loc(key)
3506 if is_integer(indexer):
3507 indexer = [indexer]
File ~\anaconda3\anaconda-py\envs\data-science\lib\site-packages\pandas\core\indexes\base.py:3623, in Index.get_loc(self, key, method, tolerance)
3621 return self._engine.get_loc(casted_key)
3622 except KeyError as err:
-> 3623 raise KeyError(key) from err
3624 except TypeError:
3625 # If we have a listlike key, _check_indexing_error will raise
3626 # InvalidIndexError. Otherwise we fall through and re-raise
3627 # the TypeError.
3628 self._check_indexing_error(key)
KeyError: 0
Run Code Online (Sandbox Code Playgroud)
这尝试访问名为的列0:
df[0]
Run Code Online (Sandbox Code Playgroud)
您的数据框没有,因此KeyError.
要通过索引访问数据帧的一行,您必须使用:
df.loc[0]
# or
df.iloc[0]
Run Code Online (Sandbox Code Playgroud)
哪一个取决于数据帧的索引值以及您想要完成的确切任务。它们还可以用于指定列。