簡體   English   中英

條形圖使用 dataframe Matplotlib

[英]Bar chart using dataframe Matplotlib

我正在研究具有以下示例數據的 pandas dataframe (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

它似乎無法識別“集群”列。 我該如何解決這個錯誤?

如果您的數據框的索引有名稱,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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM