如何按月份名称排序并修复Python Matplotlib中的KeyError
解决按月份名称排序的柱状图绘制问题
错误原因分析
- KeyError问题:执行
groupby(['Month'])后,Month会变成DataFrame的索引而非列,直接用month_df['Month']会找不到该列;另外代码里误用了未定义的year_df变量,应该统一使用month_df。 - 排序逻辑错误:直接用
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
相关产品推荐
相关产品推荐

