如何修复pandas数据框中的“键值错误”?

时间:2019-07-28 18:54:45

标签: python pandas numpy

因此,我正在尝试建立一种用于识别手势的机器学习模型。 我对机器学习和numpy很陌生。我遇到以下错误

pixel0  pixel1  pixel2  pixel3  ...  pixel9212  pixel9213  pixel9214  

pixel9215
0     255     255     255     255  ...        255        255        255        255
0     255     255     255     255  ...        255        255        255        255
0     255     255     255     255  ...        255        255        255        255
0     255     255     255     255  ...        255        255        255        255
0     255     255     255     255  ...        255        255        255        255

[5 rows x 9216 columns]
Traceback (most recent call last):
  File "classification.py", line 12, in <module>
    y = np.array(train.pop('label'))
  File "/home/bing/.local/lib/python2.7/site-packages/pandas/core/generic.py", line 809, in pop
    result = self[item]
  File "/home/bing/.local/lib/python2.7/site-packages/pandas/core/frame.py", line 2927, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/home/bing/.local/lib/python2.7/site-packages/pandas/core/indexes/base.py", line 2659, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'label'

这是我的分类。py

 import pandas as pd
 import numpy as np

 train = pd.read_csv("train60.csv")
 print(train.head())
 y = np.array(train.pop('label'))  # this is the error

我已经发布了完整的引用通告消息 帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您的火车df最有可能没有称为“标签”的列。您可以通过在脚本中进行简单的添加来检查它。

if 'label' in train.columns:
    print("label column is present")
else:
    print("label column is not here. Popping 'label' will produce KeyError")

您还想在使用弹出功能时从train df中删除“ label”吗?我说这是因为df.pop('MyColumnName')将返回'MyColumnName'并将其从df中删除。也许这正是您想要的,但我认为您应该知道。希望对您有所帮助。

答案 1 :(得分:0)

看一下文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pop.html

如果未找到传递的列名,则在pandas DataFrame上调用pop会引发KeyError。这似乎是发生了什么事,但是如果不查看您的确切DataFrame,我就无法判断。仔细检查以验证DataFrame train是否包含名为“ label”的列。