如何修复Python代码中的KeyError: (1, 0)错误?
KeyError: (1, 0) 问题修复方案
原始代码
stats = ['ETT', 'EMT', 'MRR', 'MMR', 'EER', 'ATT', 'MMT' ,'EMM' ,'ERT' ,'AER' ,'AEE' ,'AMM' ,'EEM' ,'ART' ,'AAR' ,'AEM' ,'MRT','AAT','AMR','ARR','AMT','RTT','EMR','ERR','EET','RRT','AET','MTT','AAE','AAM','EEE','TTT', 'AAA','MMM','RRR'] def determine_rewards(number_of_look_up_table,current_row_index,action_index): if stats[number_of_look_up_table][current_row_index] == 'T' : reward = rewards[0,action_index] elif stats[number_of_look_up_table][current_row_index] == 'M' : reward = rewards[1,action_index] elif stats[number_of_look_up_table][current_row_index] == 'E' : reward = rewards[2,action_index] elif stats[number_of_look_up_table][current_row_index] == 'R' : reward = rewards[3,action_index] elif stats[number_of_look_up_table][current_row_index] == 'A' : reward = rewards[4,action_index] return reward reward = determine_rewards(2,0,0)
注:rewards是5行20列的数值矩阵,调用函数时触发如下错误:
reward = determine_rewards(2,0,0) KeyError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 2656 try: -> 2657 return self._engine.get_loc(key) 2658 except KeyError: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: (1, 0) During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_28528/3264022016.py in <module> ----> 1 reward = determine_rewards(2,0,0) ~\AppData\Local\Temp/ipykernel_28528/255015173.py in determine_rewards(number_of_look_up_table, current_row_index, action_index) 20 reward = rewards[0,action_index] 21 elif stats[number_of_look_up_table][current_row_index] == 'M' : ---> 22 reward = rewards[1,action_index] 23 elif stats[number_of_look_up_table][current_row_index] == 'E' : 24 reward = rewards[2,action_index] ~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key) 2925 if self.columns.nlevels > 1: 2926 return self._getitem_multilevel(key) -> 2927 indexer = self.columns.get_loc(key) 2928 if is_integer(indexer): 2929 indexer = [indexer] ~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 2657 return self._engine.get_loc(key) 2658 except KeyError: -> 2659 return self._engine.get_loc(self._maybe_cast_indexer(key)) 2660 indexer = self.get_indexer([key], method=method, tolerance=tolerance) 2661 if indexer.ndim > 1 or indexer.size > 1: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: (1, 0)
错误原因
rewards是pandas的DataFrame对象,你误用了numpy数组的索引语法rewards[行,列]。DataFrame会把(1,0)当成列名去查找,而你的数据中没有这个列名,因此触发KeyError。
修复方案
方案1:使用DataFrame官方索引方法.iloc
.iloc是DataFrame中基于整数位置获取元素的标准方式,替换原有索引语法即可:
stats = ['ETT', 'EMT', 'MRR', 'MMR', 'EER', 'ATT', 'MMT' ,'EMM' ,'ERT' ,'AER' ,'AEE' ,'AMM' ,'EEM' ,'ART' ,'AAR' ,'AEM' ,'MRT','AAT','AMR','ARR','AMT','RTT','EMR','ERR','EET','RRT','AET','MTT','AAE','AAM','EEE','TTT', 'AAA','MMM','RRR'] def determine_rewards(number_of_look_up_table,current_row_index,action_index): char = stats[number_of_look_up_table][current_row_index] if char == 'T' : reward = rewards.iloc[0, action_index] elif char == 'M' : reward = rewards.iloc[1, action_index] elif char == 'E' : reward = rewards.iloc[2, action_index] elif char == 'R' : reward = rewards.iloc[3, action_index] elif char == 'A' : reward = rewards.iloc[4, action_index] return reward reward = determine_rewards(2,0,0)
方案2:将DataFrame转为numpy数组
如果习惯numpy的索引逻辑,可以先把rewards转成numpy数组,之后就能继续用[行,列]的语法:
# 先转换为numpy数组 rewards = rewards.to_numpy() stats = ['ETT', 'EMT', 'MRR', 'MMR', 'EER', 'ATT', 'MMT' ,'EMM' ,'ERT' ,'AER' ,'AEE' ,'AMM' ,'EEM' ,'ART' ,'AAR' ,'AEM' ,'MRT','AAT','AMR','ARR','AMT','RTT','EMR','ERR','EET','RRT','AET','MTT','AAE','AAM','EEE','TTT', 'AAA','MMM','RRR'] def determine_rewards(number_of_look_up_table,current_row_index,action_index): char = stats[number_of_look_up_table][current_row_index] if char == 'T' : reward = rewards[0,action_index] elif char == 'M' : reward = rewards[1,action_index] elif char == 'E' : reward = rewards[2,action_index] elif char == 'R' : reward = rewards[3,action_index] elif char == 'A' : reward = rewards[4,action_index] return reward reward = determine_rewards(2,0,0)
可选优化:用字典简化分支逻辑
可以用字典映射字符和行索引,替代多个elif,让代码更简洁:
stats = ['ETT', 'EMT', 'MRR', 'MMR', 'EER', 'ATT', 'MMT' ,'EMM' ,'ERT' ,'AER' ,'AEE' ,'AMM' ,'EEM' ,'ART' ,'AAR' ,'AEM' ,'MRT','AAT','AMR','ARR','AMT','RTT','EMR','ERR','EET','RRT','AET','MTT','AAE','AAM','EEE','TTT', 'AAA','MMM','RRR'] # 字符到行索引的映射表 char_to_row = {'T':0, 'M':1, 'E':2, 'R':3, 'A':4} def determine_rewards(number_of_look_up_table,current_row_index,action_index): char = stats[number_of_look_up_table][current_row_index] row_idx = char_to_row[char] # 若用numpy数组则改为 rewards[row_idx, action_index] return rewards.iloc[row_idx, action_index] reward = determine_rewards(2,0,0)
内容的提问来源于stack exchange,提问作者znb
相关产品推荐
相关产品推荐

