簡體   English   中英

使用 Matplotlib 繪制條形圖時出現關鍵錯誤

[英]Key error while plotting a bar graph using Matplotlib

在嘗試使用 matplotlib 庫對條形圖進行 plot 時,我一直面臨一個問題。

請在下面找到示例數據

樣本數據圖像

count_movies_year = n_db.groupby('release_year').agg({'title':'count'}).rename(columns={'title':'no_of_titles'})
count_movies_year.reset_index()

我已經編寫了上面的代碼並在某些情況下執行了 group_by 並重命名了 dataframe 中的列。 現在,在此之后,我想 plot 使用 matplotlib 制作相同的條形圖,並且我編寫了以下代碼

plt.bar(count_movies_year['release_year'],count_movies_year['no_of_titles'])
plt.xlabel('release_year')
plt.ylabel('no_of_titles')
plt.show()

但是,當我這樣做時,我有一些錯誤,並且 key_error 顯示我'release_year'。 我能知道這里有什么問題嗎,因為我是 Python 和 Matplotlib 的新手。 有人可以指導我到底哪里出了問題,以便我下次可以糾正它們嗎?

執行group_by時,Dataframe 中不再存在“release_year”列,因為它現在是索引。

您有多種解決方案:


像你一樣使用reset_index ,但你應該將它重新歸因於你的變量

count_movies_year = count_movies_year.reset_index()

或使用inplace參數

count_movies_year.reset_index(inplace=True)

直接在 plot 中使用.index

plt.bar(count_movies_year.index, count_movies_year['no_of_titles'])

暫無
暫無

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

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