• 主页
  • 使用Pandas创建新系列时,在使用date/datetime时遇到问题

使用Pandas创建新系列时,在使用date/datetime时遇到问题

我在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'

我不知道如何处理这个错误。我现在认为这可能是由以下两种原因造成的:一是我的无能,二是。Date没有以我认为的方式保存,因此不能正确转换。也许是AWS固有的一些东西?

有人对这里可能发生的事情有什么建议吗?如果做不到这一点,有没有人有任何建议可以避免完全使用pd.datetime的潜在解决方案?

提前感谢

转载请注明出处:http://www.jxbyjx.net/article/20230515/2009125.html