Cameron
Cameron

Reputation: 101

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

Sorry in advance for poor formatting, new to python and to posting on this site.

I use the following code to get the dataframe below:

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

I am trying to plot it using Seaborn with this code:

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

However, it always gives me the error

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

when I try to plot. I've tested it using

'Prompt' in staff.index 

which returns True

I've also tried resetting the index, but that doesn't seem to help either. Any thoughts as to what might be wrong with my code? Thanks in advance.

Upvotes: 2

Views: 5878

Answers (1)

epattaro
epattaro

Reputation: 2428

well its unclear what exactly you want to plot out of the dataframe, but there might be easier ways.

if its just a bar plot, you could just:

 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')

there are a couple misstakes in your code, which are kind of since you are new, let me help make em clear:

  • first, you make a new df, called staff. afterwards, you refer to df instead of staff, that might be a mistake

  • second, you are first creating a grid, to afterwards try to apply a map function to try to graph on it, which is not really the most common/simple way to plot a graph

  • third, inside the map function, you are passing your arguments all wrong

a good hint would be for you to check some example plot functions, either from seaborn, or matplotlib documentation, here are some referals:

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

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

hope it helps

Upvotes: 1

Related Questions