python - 在python中注释绘图时出现KeyError
问题描述
我有以下代码:
import pandas as pd
import datetime as date
from pandas_datareader import data as web
from pandas.tseries.offsets import *
import matplotlib as mpl
import matplotlib.pyplot as plt
import mplcursors
start = date.datetime(2018,1,1)
end = date.datetime.today()
xl_file = pd.read_excel(r'C:\Users\user\randomdates.xlsx')
xl_file.set_index("Date", inplace = True)
xl_file.index = pd.to_datetime(xl_file.index, format='%Y-%m-%d')
stock = 'BTC-USD'
data = web.DataReader(stock, 'yahoo', start, end)
fig , ax = plt.subplots(figsize=(18, 4))
data.plot(y='Close', ax = ax)
newdates = xl_file.loc[start:end]
for anotate in (xl_file.index):
ax.annotate(anotate, xy=(anotate, data['Close'].loc[anotate]), xycoords='data',
xytext=(-30, 40), textcoords='offset points',
size=13, ha='center', va="baseline",
bbox=dict(boxstyle="round", alpha=0.1),
arrowprops=dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1));
我提到的excel文件中有以下条目:
日期是随机的,我使用以下 excel 公式得到这些日期:
=RANDBETWEEN(DATE(2018, 1, 1),DATE(2019, 10, 20))
由于某种原因,该图是为 生成的,pandas_datareader
但它不在annotating
该图上。我不断收到以下错误,不知道该怎么做:
KeyError: 1514764800000000000
请告知我该怎么做才能解决此错误。
解决方案
尝试使用 Pandas 内置的处理日期的方法,pandas.to_datetime()
这会将您的列转换为日期格式。
这是一个很好的参考:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html
推荐阅读
- google-assistant-sdk - 如何构建只需要与我的 IoT 网关通信的 Google 智能家居操作?
- c++ - & 和 * 的区别
- python - 在 AWS 上拍摄我的 RabbitMq 实例的快照会损害我的应用程序产品吗?
- shapes - 从 P5.js 中的图像中剪出自定义形状
- javascript - AdminLTE 仪表板日历不显示在刀片 laravel
- ios - 使用结构协议的 MemoryLayout 的奇怪案例,报告了不同的大小
- python - 当健康达到0时试图在pygame中弹出敌人
- javascript - 样式被 Material-UI 样式覆盖
- heroku - Jhipster 部署到 heroku 时出错。在类路径资源中定义名称为“servletEndpointRegistrar”的 bean 创建错误
- javascript - 从对象数组中,将属性提取到多个数组中(每个属性一个)?