【发布时间】:2021-03-25 22:13:01
【问题描述】:
我在 AWS 上使用了一些财务数据,只是为了学习一些新事物。我已经使用yfinance 模块下载了这些数据。我不确定是否/如何在数据中包含一个 csv 文件,但here 是 df.head() 的一部分,希望能让您了解它的外观。这是一些按日期以YYYY-MM-DD 格式排序的每日价格。
最后,我想根据日历年将此数据框分成单独的熊猫系列。一些搜索表明我应该使用类似的东西
df['Date'] = pd.to_datetime(df['Date'], format="%Y-%m-%d")
转换为pd.datetime,我应该能够相对容易地转换为系列。
但是,我已经尝试了许多变体,但一直收到很长的回溯错误:
KeyError Traceback (most recent call last)
~/anaconda3/envs/amazonei_mxnet_p36/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2645 try:
-> 2646 return self._engine.get_loc(key)
2647 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: 'Date'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-82-c28bc405dae4> in <module>
3 SP500_df = fill_nan_with_mean(SP500)
4
----> 5 df['Date'] = pd.to_datetime(df['Date'], format="%Y-%m-%d")
~/anaconda3/envs/amazonei_mxnet_p36/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key)
2798 if self.columns.nlevels > 1:
2799 return self._getitem_multilevel(key)
-> 2800 indexer = self.columns.get_loc(key)
2801 if is_integer(indexer):
2802 indexer = [indexer]
~/anaconda3/envs/amazonei_mxnet_p36/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2646 return self._engine.get_loc(key)
2647 except KeyError:
-> 2648 return self._engine.get_loc(self._maybe_cast_indexer(key))
2649 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2650 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: 'Date'
我不确定如何处理此错误。我目前认为这可能是由以下任一原因引起的:i。我的无能,二。 Date 的东西没有被保存,我认为它是如何保存的,因此没有正确转换或 iii。可能是 AWS 固有的东西?
有人对这里可能发生的事情有什么建议吗?如果做不到这一点,是否有人对任何可以避免完全使用pd.datetime 的潜在解决方法提出建议?
提前致谢
【问题讨论】:
-
您的 df 似乎有一个索引“日期”,而不是一列。您应该可以使用
df.index = pd.to_datetime(df.index)将其转换为日期时间。
标签: python pandas dataframe datetime series