Search code examples
pythonpandaserror-handlingkeyerror

KeyError: "None of [Index(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday'], dtype='object')] are in the [index]"


I have a pandas dataframe which looks like this:

weekday     mean sum
Friday      160 26572
Monday      150 73762
Saturday    55  67256
Sunday      626 22222
Thursday    133 34566

weekday is the index and mean and sum are the columns.

What I now tried to do was to plot the dataframe and order the bars properly using this code:

df2['sum'].value_counts()[['Monday', 'Tuesday', 'Wednesday','Thursday','Friday','Saturday','Sunday']].plot(kind="bar")

But I got this error:

KeyError: "None of [Index(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',\n       'Sunday'],\n      dtype='object')] are in the [index]"

How can I eliminate this error?


Solution

  • You need either .loc or .reindex to reorder the series:

    (df2['sum']
      .loc[['Monday', 'Tuesday', 'Wednesday','Thursday','Friday','Saturday','Sunday']]
      .plot(kind="bar")
    )