Pandas/Seaborn KeyError: '[example]' not in index

Pandas/Seaborn KeyError: '[example]' not in index

对于 python 的新手以及在此网站上发布的格式不佳,提前致歉。

我使用以下代码获取下面的数据框:

staff=df.loc['Adults in my after school program are nice.':'I like the adults in my after school program.', 'Percent':'Performance']

Prompt                                        Percent        Performance
Adults are nice.                              87             Good
Adults treat me fairly.                       70             Needs Improvement
Adults listen to what I have to say.          90             Excellent
I like the adults.                            80             Good

我正在尝试使用 Seaborn 和以下代码绘制它:

fg = seaborn.FacetGrid(data=df, hue='Performance', aspect=1.61)
fg.map(plt.bar, 'Staff', 'Percent').add_legend()
fg

然而,它总是给我错误

KeyError: "['Staff'] not in index"

当我尝试绘图时。我已经使用

对其进行了测试
'Prompt' in staff.index 

哪个returnsTrue

我也尝试过重新设置索引,但这似乎也无济于事。关于我的代码可能有什么问题的任何想法?提前致谢。

目前还不清楚您想从数据框中绘制出什么,但可能有更简单的方法。

如果它只是一个条形图,你可以:

 sns.barplot(data=staff, y='column name you want to associate to y', x='column name you want to associate to x, if any', hue='hue you want to apply if any')

你的代码中有一些错误,因为你是新手,所以让我帮助你弄清楚:

  • 首先,您创建一个新的 df,称为 staff。之后你说的是df而不是staff,那可能是个错误

  • 其次,您首先创建一个网格,然后尝试应用地图函数尝试在其上绘制图形,这并不是最 common/simple 绘制图形的方式

  • 第三,在 map 函数中,你传递的参数全错了

一个很好的提示是检查一些示例绘图函数,来自 seaborn 或 matplotlib 文档,这里有一些参考资料:

http://seaborn.pydata.org/generated/seaborn.barplot.html

http://matplotlib.org/examples/api/barchart_demo.html

希望对您有所帮助