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

Matplotlib绘制柱状图遇KeyError: 'date'问题,求解决方法

解决DataFrame绘制柱状图时的KeyError: 'date'问题

核心修复点

  • 变量名错误:你创建的DataFrame变量是df1,但绘图时调用的是未定义的df,这是导致找不到'date'列的直接原因。把所有df.plot()中的df替换为df1即可。

其他排查方向

  • 验证数据集结构:确保lst中的每一行数据都包含4个元素,与你指定的列名['source','type','date','count']一一对应。可以在创建DataFrame后添加print(df1.columns),确认输出的列名列表里确实有'date'。
  • 检查列名拼写:确认列名没有大小写错误(比如写成Date)或拼写失误(比如dtae),pandas对列名的大小写是敏感的。
  • 修正绘图逻辑:如果source是字符串类型,直接将其作为y轴绘制柱状图会无效(因为需要数值型数据)。如果source是类别字段,你需要先按date和source分组统计(比如计数或求和)再绘图;如果是数值型字段,先确保数据类型正确,可通过df1['source'] = pd.to_numeric(df1['source'], errors='coerce')转换并处理异常值。

修正后的示例代码

import matplotlib.pyplot as plt
import pandas as pd
import random

def la_bar():
    # 示例数据集,替换为你的真实lst
    lst = [
        ['source_A', 'type_1', '2024-01', 12],
        ['source_B', 'type_2', '2024-02', 25],
        ['source_A', 'type_1', '2024-03', 18]
    ]
    df1 = pd.DataFrame(lst, columns=['source','type','date','count'])
    
    # 先确认列存在
    print(df1.columns)
    
    # 绘制双组柱状图(假设source是数值型,若为类别需调整逻辑)
    ax = df1.plot(x="date", y="count", kind="bar", label="Count", color='#1f77b4')
    df1.plot(x="date", y="source", kind="bar", ax=ax, label="Source", color='#ff7f0e')
    
    plt.title("Date vs Count/Source")
    plt.legend()
    plt.savefig("static/images/image.png")

la_bar()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:52:45