Python Pandas绘制柱状图时出现KeyError报错的求助
解决Pandas DataFrame.plot()柱状图的KeyError问题
问题根源
你调用frame.plot(frame['city'], kind='bar', legend=True)的方式不符合Pandas的参数规则。DataFrame.plot()的第一个参数并非直接传入列数据,而是x轴对应的列名字符串。你把frame['city']的实际取值(如Zomba、Lilongwe等城市名)传进去后,Pandas会将这些值当作列名去DataFrame中查找,而你的数据里根本没有这些列,因此触发KeyError。
正确解决代码
直接通过x参数指定列名'city',同时明确要绘制的数值列(比如'rank',柱状图需要基于数值数据生成):
# 绘制rank列随city的柱状图 frame.plot(x='city', y='rank', kind='bar', legend=True)
如果需要对比所有数值列(比如同时展示rank和其他数值列),可以省略y参数,Pandas会自动绘制所有数值列:
frame.plot(x='city', kind='bar', legend=True)
补充说明
你用frame.get('city')和frame.iloc[:,0]能正常获取数据,说明city列确实存在,但plot方法的参数逻辑是接收列名字符串,而非列数据本身。之前的写法相当于让Pandas“去找名为Zomba、Lilongwe的列”,显然你的DataFrame只有city、rank、region三列,所以必然报错。
内容的提问来源于stack exchange,提问作者Michael Harawa
相关产品推荐
相关产品推荐

