Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError: 0L building boxplot

I'm using version 0.18.0 of pandas and 1.5.1 of matplotlib.

When attempting to create a boxplot, I receive KeyError: 0L.

df = df[(df['colA'] > 1000) & (df['colA'] < 5000)]
plt.boxplot(df['ColA'])

when I do not perform a filter on the df, the code runs and a boxplot is created without any issues.

When I use the filtered df to plot a histogram, this works without any errors.

plt.hist(df['ColA'], range(1000,5000,500))

What is causing the error when trying to create the boxplot? Any help appreciated.

like image 826
luke_t Avatar asked Sep 07 '25 22:09

luke_t


1 Answers

In case you missed it while Googling (like I almost did), the answer is in the comments on the question:

  • Use .values: plt.boxplot(df['ColA'].values).
  • Find more explanation and options in this question.
    • tldr; Plot tries to go from index 0 onwards, which doesn't work for named columns or slices, etc... Using .values or reseting the index will solve this.

Kudos to @ayhan for this information.

like image 59
Bilal Akil Avatar answered Sep 10 '25 02:09

Bilal Akil