我正在研究具有以下示例资料的熊猫资料框(data_agg_clust):
KPIPred
Cluster
9-11 125.872327
18-20 120.084786
15-17 112.328802
12-14 109.752560
21-23 106.128234
我想使用 matplotlib 创建一个条形图:
import matplotlib.pyplot as plt; plt.rcdefaults()
data_agg_clust.plot.bar(x="Cluster", y="KPIPred", rot=70, title="Predicted Volume of impressions");
plot.show(block=True);
但不幸的是,我收到了这个错误:
KeyError Traceback (most recent call last)
~/.pyenv/versions/anaconda3-2021.05/envs/jupiter/lib/python3.10/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3360 try:
-> 3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:
~/.pyenv/versions/anaconda3-2021.05/envs/jupiter/lib/python3.10/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
~/.pyenv/versions/anaconda3-2021.05/envs/jupiter/lib/python3.10/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'Cluster'
The above exception was the direct cause of the following exception
它似乎无法识别“集群”列。我该如何解决这个错误?
uj5u.com热心网友回复:
如果您的资料框的索引有名称,pandas 将通过在列名称下方的一行上打印来直观地区分它。在这种情况下Cluster
是您的索引的名称。
最简单的解决方案是不理x
会:如果您不提供列名,它将默认为索引:
data_agg_clust.plot.bar(y="KPIPred", rot=70, title="Predicted Volume of impressions")
另一种解决方案是呼叫data_agg_clust.reset_index
将索引转换为可用于绘图的列:
data_agg_clust.reset_index().plot.bar(x="Cluster", y="KPIPred", rot=70, title="Predicted Volume of impressions")
0 评论