【发布时间】: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