【问题标题】:how do i solve key error due to missing list我如何解决由于缺少列表而导致的关键错误
【发布时间】:2021-10-31 23:04:51
【问题描述】:

我认为我的问题是不是我正在分析的每个文件都包含我的 sleep_stages 列表中的每个项目,但我不知道如何解决它。例如,某些文件不会包含任何提及睡眠阶段 N1 或列表中的其他项目。我希望能够为该值输入 na ,但从列表中的项目中捕获其他值。 见代码:

def get_sleep_times(hypno):
    sleep_stages=['Sleep stage N1','Sleep stage R','Sleep stage N2', 'Sleep 
               stage N3',  'Sleep stage ?']
    sleep_times = {}
    totsleep_time = 0
    tmp = hypno.groupby('description')['duration'].sum()
    for stage in sleep_stages:
        sleep_times['Duration of ' +stage]=tmp.loc[stage]
        totsleep_time += tmp.loc[stage]
    sleep_times['Total Sleep Duration'] = totsleep_time
    return sleep_times
see error message:






KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3360             try:
-> 3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:

~\Anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

~\Anaconda3\lib\site-packages\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: 'Sleep stage ?'

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

KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_21360/487801242.py in <module>
----> 1 hypno_report(dfpmnospcl)

~\AppData\Local\Temp/ipykernel_21360/1936770717.py in hypno_report(df)
     16                 print(fnames, matches)
     17             hypno = pd.read_csv(matches[0], delimiter='\t',encoding='utf-8')
---> 18             result.update(get_sleep_times(hypno))
     19             result.update(get_hypno_counts(hypno, events))
     20         results.append(result)

~\AppData\Local\Temp/ipykernel_21360/2297364264.py in get_sleep_times(hypno)
     12 
     13     else:
---> 14             sleep_times['Duration of ' +stage]=tmp.loc[stage]
     15             totsleep_time += tmp.loc[stage]
     16 

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
    929 
    930             maybe_callable = com.apply_if_callable(key, self.obj)
--> 931             return self._getitem_axis(maybe_callable, axis=axis)
    932 
    933     def _is_scalar_access(self, key: tuple):

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1162         # fall thru to straight lookup
   1163         self._validate_key(key, axis)
-> 1164         return self._get_label(key, axis=axis)
   1165 
   1166     def _get_slice_axis(self, slice_obj: slice, axis: int):

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
   1111     def _get_label(self, label, axis: int):
   1112         # GH#5667 this will fail if the label is not present in the axis.
-> 1113         return self.obj.xs(label, axis=axis)
   1114 
   1115     def _handle_lowerdim_multi_index_axis0(self, tup: tuple):

~\Anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
   3774                 raise TypeError(f"Expected label or tuple of labels, got {key}") from e
   3775         else:
-> 3776             loc = index.get_loc(key)
   3777 
   3778             if isinstance(loc, np.ndarray):

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:
-> 3363                 raise KeyError(key) from err
   3364 
   3365         if is_scalar(key) and isna(key) and not self.hasnans:

KeyError: 'Sleep stage ?'

【问题讨论】:

    标签: python key


    【解决方案1】:

    这可能无法正常工作,因为我不知道 hypno 的样子。如果你下次能描述一下它的结构会很有帮助。

    def get_sleep_times(hypno):
        
    
        sleep_stages=['Sleep stage N1', 'Sleep stage R', 'Sleep stage N2', 'Sleep stage N3', 'Sleep stage ?']
    
        tmp = hypno.groupby('description')['duration'].sum()
    
        sleep_times = {'Duration of ' + stage: tmp.loc[stage] if stage in tmp.columns else None for stage in sleep_stages}
        sleep_times['Total sleep duration: '] = sum(sleep_times.values())
        
        return sleep_times
    
    

    sleep_times 字典将包含每个阶段的持续时间(如果阶段名称存在于tmp 的列名中)或None 否则。

    然后将汇总字典中的值并添加为新条目(总睡眠持续时间)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      • 2018-03-04
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      相关资源
      最近更新 更多