首页 > 解决方案 > 使用日期/日期时间无法使用 Pandas 创建新系列

问题描述

我在 AWS 上使用了一些财务数据,只是为了学习一些新东西。我已经使用该yfinance模块下载了这些数据。我不确定是否/如何在数据中包含一个 csv 文件,但这里是 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完全避免使用的潜在解决方法提出建议?

提前致谢

标签: pythonpandasdataframedatetimeseries

解决方案


MrFuppes 是正确的。这已经足够了df.index = pd.to_datetime(df.index)。我实际上在调用列之前尝试过重置索引,这给了我同样的错误,但至少这是可行的。


推荐阅读