python - 使用日期/日期时间无法使用 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
完全避免使用的潜在解决方法提出建议?
提前致谢
解决方案
MrFuppes 是正确的。这已经足够了df.index = pd.to_datetime(df.index)
。我实际上在调用列之前尝试过重置索引,这给了我同样的错误,但至少这是可行的。
推荐阅读
- java - 如何使用 session.setAttribute("id", id) onclick java servlet中的按钮?
- rest - 当查询字符串中缺少参数时使用什么状态码?
- objective-c - 如何继续将值从一个 ViewController 传递到第二个 ViewController 并自动关闭,关闭第二个 ViewController
- javascript - 使用 javascript 功能引导自定义标记
- r - 如何在 Shiny Dashboard 的框中将表格居中
- android - Cordova 缺少资产内容
- python - 我能够在 Windows 的命令提示符下运行 python,但无法在 atom 编辑器的终端中运行它
- c# - 在运行时调用 bridge.net 编译器
- sql-server - SQL Server - 每个 GROUP BY 表达式必须至少包含一个不是外部引用的列
- excel - 计算具有特定值的excel中的行