Traceback (most recent call last): raise KeyError(key) from err KeyError:2 -重置索引(pandas、dataframe)

python——重置索引


在用 pandas 处理表格数据时,遇到了这种错误如何解决?
报错信息如下:

Traceback (most recent call last):
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\base.py", line 3621, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 136, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 163, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 2131, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 2140, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 2

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\MyCode\Python_Code\PyCharm\CSDN.py", line 16, in <module>
    print(df.at[i, 'name'], df.at[i, 'score'])
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexing.py", line 2262, in __getitem__
    return super().__getitem__(key)
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexing.py", line 2213, in __getitem__
    return self.obj._get_value(*key, takeable=self._takeable)
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py", line 3623, in _get_value
    row = self.index.get_loc(index)
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\base.py", line 3623, in get_loc
    raise KeyError(key) from err
KeyError: 2

你是否对数据进行了删除、修改操作,然后对表格进行了遍历或者访问了某行数据。
如果是的话,那么可以用下面这个方法来解决:重置表格索引
如果不是,也可以用这个方法试一下是否可以解决~

方法一

df.index = range(len(df))

方法二

df = df.reset_index()				# 索引列加入到表格中

df = df.reset_index(drop=True)		# 索引列不加入表格

原因是可能你删除了某行数据或者修改了某行的索引,相应的那行的索引没了,而pandas不会自动修复索引,那么在你对表格进行遍历操作或者运算的时候,因为找不到被你删除掉的那行(索引不存在),所以会报错!


下面来看看这几种方法的效果:

方法一

import pandas as pd

df = pd.DataFrame({"name": ['张三', '李四', '王五', '赵六'], "score": [90, 100, 50, 60]})
print(f'原表格如下:\n{df}')

df.drop(2, axis=0, inplace=True)    # 删除“王五”的记录
print(f'\n删除后如下:\n{df}')

df.index = range(len(df))
print(f'\n修改后如下:\n{df}')

输出如下:

原表格如下:
  name  score
0   张三     90
1   李四    100
2   王五     50
3   赵六     60

删除后如下:
  name  score
0   张三     90
1   李四    100
3   赵六     60

修改后如下:
  name  score
0   张三     90
1   李四    100
2   赵六     60

方法二

import pandas as pd

df = pd.DataFrame({"name": ['张三', '李四', '王五', '赵六'], "score": [90, 100, 50, 60]})
print(f'原表格如下:\n{df}')

df.drop(2, axis=0, inplace=True)    # 删除“王五”的记录
print(f'\n删除后如下:\n{df}')

df = df.reset_index(drop=True)
print(f'\n修改后如下:\n{df}')

输出如下:

原表格如下:
  name  score
0   张三     90
1   李四    100
2   王五     50
3   赵六     60

删除后如下:
  name  score
0   张三     90
1   李四    100
3   赵六     60

修改后如下:
  name  score
0   张三     90
1   李四    100
2   赵六     60

效果和方法一是一样的!

如果你想要保留旧的索引,那么可以这样:

import pandas as pd

df = pd.DataFrame({"name": ['张三', '李四', '王五', '赵六'], "score": [90, 100, 50, 60]})
print(f'原表格如下:\n{df}')

df.drop(2, axis=0, inplace=True)    # 删除“王五”的记录
print(f'\n删除后如下:\n{df}')

df = df.reset_index()
print(f'\n修改后如下:\n{df}')

输出如下:

原表格如下:
  name  score
0   张三     90
1   李四    100
2   王五     50
3   赵六     60

删除后如下:
  name  score
0   张三     90
1   李四    100
3   赵六     60

修改后如下:
   index name  score
0      0   张三     90
1      1   李四    100
2      3   赵六     60

可以看见旧的索引就添加到表格中了,列名叫 index

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值