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

如何按月份名称排序并修复Python Matplotlib中的KeyError

解决按月份名称排序的柱状图绘制问题

错误原因分析

  1. KeyError问题:执行groupby(['Month'])后,Month会变成DataFrame的索引而非列,直接用month_df['Month']会找不到该列;另外代码里误用了未定义的year_df变量,应该统一使用month_df。
  2. 排序逻辑错误:直接用sort_values(by="Month")是按字符串字典序排序,会导致月份顺序混乱(比如January不会排在第一位),必须按实际月份的自然顺序排序。

修正步骤与代码

步骤1:将Month从索引转回列

两种方式任选其一:

# 方式1:分组时直接保留Month为列
month_df = tweets_df.groupby(['Month'], as_index=False)[["Tweet"]].count()

# 方式2:对已生成的month_df重置索引
# month_df = month_df.reset_index()

步骤2:按自然月份顺序排序

利用日历模块获取标准月份顺序,将Month列转为分类类型并指定顺序,确保排序符合实际月份逻辑:

from calendar import month_name
# 获取从January到December的标准月份列表
month_order = list(month_name)[1:]  # 剔除列表第一个空元素

# 将Month列转为分类类型,绑定指定顺序
month_df['Month'] = pd.Categorical(month_df['Month'], categories=month_order, ordered=True)

# 按月份顺序排序
month_df = month_df.sort_values('Month')

步骤3:绘制柱状图

修正变量名错误,使用正确的列数据绘图:

import matplotlib.pyplot as plt

plt.rc('figure', figsize=(16, 8))
plt.bar(month_df['Month'], month_df['Tweet'])
plt.xticks(month_df['Month'])
plt.ylabel('推文数量')
plt.xlabel('月份')
plt.show()

完整修正代码

import pandas as pd
import matplotlib.pyplot as plt
from calendar import month_name

# 分组统计,保留Month为列
month_df = tweets_df.groupby(['Month'], as_index=False)[["Tweet"]].count()

# 定义月份顺序并转换为分类类型
month_order = list(month_name)[1:]
month_df['Month'] = pd.Categorical(month_df['Month'], categories=month_order, ordered=True)

# 按月份顺序排序
month_df = month_df.sort_values('Month')

# 绘制柱状图
plt.rc('figure', figsize=(16, 8))
plt.bar(month_df['Month'], month_df['Tweet'])
plt.xticks(month_df['Month'])
plt.ylabel('推文数量')
plt.xlabel('月份')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:30:55