【问题标题】:KeyError: 0 when try to access a row in pandas DataFrameKeyError: 0 尝试访问 pandas DataFrame 中的一行
【发布时间】:2023-02-04 03:23:17
【问题描述】:

我正在关注一本书 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]

以下是我在 jupyter notebook 中运行单元格时遇到的错误。

---------------------------------------------------------------------------
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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这会尝试访问名为 0 的列:

    df[0]
    

    你的数据框没有,因此是KeyError

    要通过索引访问数据框的一行,您必须使用:

    df.loc[0]
    
    # or
    
    df.iloc[0]
    

    哪一个取决于数据框的索引值以及您想要完成的确切事情。它们也可用于指定列。

    【讨论】:

      【解决方案2】:

      跟随本书时,我遇到了同样的错误。 我使用@baileythegreen 的回答来让它工作。

      您只需将X.loc[0].array 分配给some_digit

      some_digit = X.loc[0].array
      

      然后其余代码将正常工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多