You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib DatetimeIndex报错:索引值不在列中求助

解决Pandas重采样后Matplotlib绘图的KeyError问题

你遇到的这个KeyError问题,根源是在调用df.plot()时错误地指定了x=df.index.values参数。Pandas的plot()方法里的x参数要求传入列名,但你的Date已经被设置为DataFrame的行索引,并不属于列列表,所以才会报错说"DatetimeIndex中的值均不在列中"。

快速修复方案

直接去掉x参数即可,当DataFrame的索引是时间类型时,plot()会自动把索引作为x轴:

# 修正后的可视化代码
ax = df.plot(y='Spend', legend=False)
# 可按需添加轴标签和标题
plt.xlabel('Date')
plt.title('Monthly Spend Trend')
plt.show()

为什么之前的写法会报错?

从你提供的df.info()输出能看到,DataFrame的列只有Spend、Traffic、Sales三个,Date是行索引而非列。当你传入x=df.index.values时,Pandas会在列中查找对应的值,自然找不到,于是触发KeyError。

另一种更灵活的实现方式

如果你想使用Matplotlib原生绘图逻辑,也可以直接指定索引作为x轴数据:

plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Spend'])
plt.xlabel('Date')
plt.ylabel('Total Monthly Spend')
plt.title('Monthly TV Ad Spend Trend')
plt.xticks(rotation=45)  # 旋转x轴标签避免重叠
plt.show()

内容的提问来源于stack exchange,提问作者cphill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:32:28