【问题标题】:A Key Error is returned when I try and use df.index.get_loc(recession_start)当我尝试使用 df.index.get_loc(recession_start) 时返回一个键错误
【发布时间】:2020-01-19 00:32:52
【问题描述】:

我试图通过观察 df 列中连续值的趋势来找出经济衰退何时结束。我想返回GDP连续两个季度上升的那个季度。

我已经在以下函数中确定了衰退何时开始:

def get_recession_start():
    df = get_data()
    for i in range(1, len(df) - 1):
        if (df.iloc[i]['GDP'] < df.iloc[i - 1]['GDP']) and (df.iloc[i + 1]['GDP'] < df.iloc[i]['GDP']):
            return df['Yearly quarters'].iloc[i]


get_recession_start()

我想用这个函数找到上述函数(get_recession_start())的精确索引,从那个点开始搜索df。

def get_recession_end():
    import pandas as pd
    import numpy as np

    df = get_data()
    recession_start = get_recession_start()
    index = df.index.get_loc(recession_start)
    for i in range(index + 2, len(df)):
        if (df.iloc[i]['GDP'] > df.iloc[i-1]['GDP']) and (df.iloc[i - 
1]['GDP'] > df.iloc[i - 2]['GDP']):
            return df['Yearly quarters'].iloc[i]

get_recession_end()

I would expect this function to return the single string value '2008q3', however, instead I'm getting a traceback message:


KeyError                                  Traceback (most recent call last)
//anaconda3/lib/python3.7/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/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

KeyError: '2008q3'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-16-5f3688935fbb> in <module>
     11             return df['Yearly quarters'].iloc[i]
     12 
---> 13 get_recession_end()

<ipython-input-16-5f3688935fbb> in get_recession_end()
      6     df = get_data()
      7     recession_start = get_recession_start()
----> 8     index = df.index.get_loc(recession_start)
      9     for i in range(index + 2, len(df)):
     10         if (df.iloc[i]['GDP'] > df.iloc[i-1]['GDP']) and (df.iloc[i - 1]['GDP'] > df.iloc[i - 2]['GDP']):

//anaconda3/lib/python3.7/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/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

KeyError: '2008q3'

【问题讨论】:

  • 请发布更多数据,不是因为我们都想知道在当前的经济解决方案下衰退何时结束;-),而是因为有了更多数据(尤其是输入数据框和预期输出),我们可以提出更好的答案。

标签: python pandas jupyter-notebook


【解决方案1】:

请注意,get_recession_startYearly Quarters 列返回一个值 (来自衰退开始季度的行)。

你在recession_start = get_recession_start()调用这个函数,所以recession_start 包含衰退开始的季度(类似于 yyyyqn)。

那么你的代码包含index = df.index.get_loc(recession_start),所以你调用 get_loc,传递刚刚找到的季度“名称”。

这就是错误的来源,因为 get_loc 在索引中查找 (可能是一个数字序列)只是这个传递的值(可能是 2008q3)。

显然,这个索引不包含传递的值,所以异常 提出的只是 KeyError: '2008q3'

纠正你的程序:

  • 找到该行的键值
  • 将其传递给 get_loc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2017-08-15
    • 2019-10-29
    相关资源
    最近更新 更多