我正在学习一本关于机器学习的书--学习机器学习,下面是显示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]下面是在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发布于 2022-04-04 17:08:12
这将尝试访问名为0的列。
df[0]而您的dataframe没有,因此KeyError。
若要按其索引访问dataframe的行,必须使用:
df.loc[0]
# or
df.iloc[0]哪一个取决于dataframe的索引值,也取决于您想要完成的确切任务。它们也可用于指定列。
https://stackoverflow.com/questions/71740971
复制相似问题