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

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

我有一个 pandas 数据框,如下所示:

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

weekday 是索引,meansum 是列。

我现在尝试做的是绘制数据框并使用以下代码正确排序条形:

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

但是我得到了这个错误:

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

如何消除这个错误?

您需要 .loc.reindex 来重新排序该系列:

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