python - 如何解决此 KeyError?
问题描述
我正在尝试使用 python 来构建一个金融投资组合优化的程序。我想出了一个关键错误:日期。这是发生关键错误的段:
#create a dataframe to store the adjusted close price of the stocks
df = pd.DataFrame()
#store the adjusted close price of the stock into the df
for stock in assets:
df[stock] = web.DataReader(stock, data_source='yahoo', start= stockStartDate , end = today)['Adj Close']
这是错误消息:
KeyError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2897 try:
-> 2898 return self._engine.get_loc(casted_key)
2899 except KeyError as err:
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: 'Date'
上述异常是以下异常的直接原因:
KeyError Traceback (most recent call last)
6 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2898 return self._engine.get_loc(casted_key)
2899 except KeyError as err:
-> 2900 raise KeyError(key) from err
2901
2902 if tolerance is not None:
解决方案
推荐阅读
- python - 涉及将 DNA 转录为 mRNA 的家庭作业项目;得到“TypeError:字符串索引必须是整数”
- java - docker compose中的Bitcoinj OverlappingFileLockException
- python - 除了 BaseException as e: 不断抛出错误
- javascript - page.evaluate 返回空值但浏览器控制台返回正确值
- express - 如何使用 Nuxt Auth 模块在 Vuex 中保存 JWT 令牌?
- firebase - 使用getSignedUrl作为缩略图的firebase云功能在大约一周后到期,没有明确的原因?
- node.js - 使用表 B 获取表 A 值,其中 A.field_name = B.field_name
- javascript - Semantic-UI-React 网格列填充不设置列内联
- android - 我想从 firebase-database 获取“bookname”子项的值,但它返回 null 并且应用程序将崩溃,所以请帮助我
- python - for 循环错过了第一次迭代