python - 如何在第 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 笔记本。谢谢。
解决方案
您需要重置您的索引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
推荐阅读
- gcc - 在 64 位 (x86-64) 机器上构建 32 位 (x86) gcc-10.2.0 时出错
- php - Phpdesktop chrome 不加载字体
- javascript - Javascript:使用变量的内容作为名称
- css - 如何通过反应原生天才聊天设置气泡中显示的图像尺寸?
- python - 与文件名匹配的子字符串列表 - python
- r - 从两个不同的数据集中减去列
- node.js - 只有一个 LIKE pr。Node.js 应用程序中的电影帖子
- python - 使用递归验证二叉搜索树
- python - BAT 文件在激活 kivy 脚本时自行终止
- flutter - 必须初始化不可为空的实例字段“categoryTitle”。尝试添加初始化表达式或生成构造函数来初始化它