Pandas分组茶叶出口数据绘图报错及正确绘图方法咨询
茶叶出口数据分组绘图报错问题解决
问题背景
拥有某茶叶出口公司数据集,包含日期、茶类(Type)、重量规格(Weight)、数量(Quantity)等字段。已通过以下代码按YearMonth、Type、Weight分组聚合Quantity:
df = pd.DataFrame(data) df['Date'] = pd.to_datetime(df['Date']).dt.date df['YearMonth'] = df['Date'].map(lambda date: 100*date.year + date.month) df = df.groupby(['YearMonth','Type', 'Weight']).agg({'Quantity':'sum'})
想要绘制以YearMonth为X轴,茶类和重量规格区分系列、数量为Y轴的图表,但执行以下代码时出现KeyError: 'Type'错误:
fig, ax = plt.subplots(figsize=(10,4)) for key, df in df.groupby(['Quantity']): ax.plot(df['Type'], df['Weight'], label=key) ax.legend() plt.show()
报错原因
- 数据结构问题:执行
groupby聚合后,YearMonth、Type、Weight这三个分组字段会被设为多级索引,不再是DataFrame的普通列。直接用df['Type']调用会找不到对应列,触发KeyError。 - 绘图逻辑错误:错误地按
Quantity分组,且代码中把Type作为X轴、Weight作为Y轴,完全不符合“YearMonth为X轴、Quantity为Y轴”的需求。
正确绘图方法
方法1:重置索引,将索引转为普通列
先把多级索引转成常规列,再按Type和Weight的组合分组绘图:
import pandas as pd import matplotlib.pyplot as plt # 对聚合后的DataFrame重置索引,将索引字段转为列 df_reset = df.reset_index() fig, ax = plt.subplots(figsize=(10,4)) # 遍历每个茶类+重量规格的组合 for (tea_type, weight), group_df in df_reset.groupby(['Type', 'Weight']): # 按年月排序,保证X轴顺序正确 sorted_group = group_df.sort_values('YearMonth') # 绘制折线:X为年月,Y为总数量,标签标注茶类和规格 ax.plot(sorted_group['YearMonth'], sorted_group['Quantity'], label=f"{tea_type} - {weight}") # 优化X轴显示,避免标签重叠 plt.xticks(rotation=45) ax.set_xlabel('年月') ax.set_ylabel('总出口数量') ax.set_title('各规格茶叶月度出口数量趋势') ax.legend() plt.tight_layout() plt.show()
方法2:直接操作多级索引(不重置索引)
如果不想修改数据结构,可以直接从多级索引中提取需要的信息:
import pandas as pd import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(10,4)) # 获取所有唯一的茶类+重量规格组合 unique_combos = df.index.unique(level=['Type', 'Weight']) for tea_type, weight in unique_combos: # 筛选对应组合的数据 subset = df.loc[(slice(None), tea_type, weight), :] # 从索引中提取年月作为X轴 x_values = subset.index.get_level_values('YearMonth') y_values = subset['Quantity'] ax.plot(x_values, y_values, label=f"{tea_type} - {weight}") plt.xticks(rotation=45) ax.set_xlabel('年月') ax.set_ylabel('总出口数量') ax.set_title('各规格茶叶月度出口数量趋势') ax.legend() plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者John Snape
相关产品推荐
相关产品推荐

