Pandas groupby后绘图出现KeyError: 'Scholarship'问题求助
解决Pandas groupby后绘图出现KeyError: 'Scholarship'的问题
核心原因
你猜的没错,groupby默认会把分组字段(这里是Scholarship)设为DataFrame的索引,而非普通列,所以绘图时指定x='Scholarship'会找不到这个字段。重置索引没生效大概率是没把重置后的结果赋值回原变量。
具体解决方法
方法1:正确重置索引
重置索引时必须把结果重新赋值给df,不然原DataFrame的结构不会改变:
# 把Scholarship从索引转回普通列 df = df.reset_index() # 此时再执行绘图代码就不会报错 df.plot(kind='bar', x='Scholarship', y='Percent Missed Appointment')
方法2:直接用索引作为x轴(无需重置索引)
既然Scholarship已经是索引,绘图时可以直接省略x参数,Pandas会自动用索引作为x轴:
df.plot(kind='bar', y='Percent Missed Appointment')
或者显式指定使用索引:
df.plot(kind='bar', x=df.index, y='Percent Missed Appointment')
方法3:提前修改groupby参数
如果一开始就不想让Scholarship变成索引,可以在groupby时设置as_index=False:
# 分组时直接保留Scholarship为普通列 df = original_df.groupby('Scholarship', as_index=False).agg(...) # 后续添加列、绘图都无需处理索引问题 df.plot(kind='bar', x='Scholarship', y='Percent Missed Appointment')
排查步骤
如果还是有问题,先打印以下信息确认DataFrame结构:
- 查看所有列名:
print(df.columns) - 查看当前索引:
print(df.index) - 查看前几行数据:
print(df.head())
内容的提问来源于stack exchange,提问作者Wildo_Baggins311
相关产品推荐
相关产品推荐

