首页 > 解决方案 > 如何在第 1414 个元素后解决 pandas 数据帧上的此关键错误

问题描述

您好,我的名为 CAR 的数据框有 2213 行,但是每当我尝试访问第 1413 个元素之后的行时,都会出现错误。到目前为止,我还没有在网站上发现类似的错误,但我的数据框非常标准(没有 Na,只有字符串或整数,大小为 7 x 2213)所以我不知道如何解决这个问题。

CAR['Code RS'][1414]
len(CAR)

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-22-0cf1ffa9a735> in <module>
----> 1 CAR['Code RS'][1414]
      2 len(CAR)

~\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    869         key = com.apply_if_callable(key, self)
    870         try:
--> 871             result = self.index.get_value(self, key)
    872 
    873             if not is_scalar(result):

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   4403         k = self._convert_scalar_indexer(k, kind="getitem")
   4404         try:
-> 4405             return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
   4406         except KeyError as e1:
   4407             if len(self) > 0 and (self.holds_integer() or self.is_boolean()):

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 1414

如果有帮助,我正在使用 Jupyter 笔记本。谢谢。

标签: pythonpandasdataframe

解决方案


您需要重置您的索引DataFrame

CAR = CAR.reset_index(drop=True)

为了演示这个问题,这里有一个例子:

df = pd.DataFrame({'a':[1,2], 'b':[6,7]})
   a  b
0  1  6
1  2  7
df2 = df.copy()
   a  b
0  1  6
1  2  7

让我们连接它们。仔细查看结果的索引DataFrame

df3 = pd.concat([df, df2])
   a  b
0  1  6
1  2  7
0  1  6
1  2  7

我们可以通过重置索引来解决这个问题:

df4 = df3.reset_index(drop=True)
   a  b
0  1  6
1  2  7
2  1  6
3  2  7

这只是一个测试用例场景,这个问题可能还有其他原因,比如:

df4.drop([2])
   a  b
0  1  6
1  2  7
3  2  7

推荐阅读