首页 > 解决方案 > 在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

请告知我该怎么做才能解决此错误。

标签: pythonpython-3.xpandasdatetimeannotations

解决方案


尝试使用 Pandas 内置的处理日期的方法,pandas.to_datetime()这会将您的列转换为日期格式。

这是一个很好的参考:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html


推荐阅读