我正在研究具有以下示例資料的熊貓資料框(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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/418148.html
標籤:
