![](/img/trans.png)
[英]How do I groupby, count or sum and then plot two lines in Pandas?
[英]How to do I groupby, count and then plot a bar chart in Pandas?
我有一個如下所示的Pandas
數據框。
year month class ---- ----- ----- 2015 1 1 2015 1 1 2015 1 2 2015 1 2 ...
我希望能夠在一個圖上創建此數據的 2 個條形圖系列。 如果我可以做一個groupby
, count
並最終得到一個data frame
那么我想我可以做一個簡單的dataframe.plot.barh
。
我嘗試過的是以下代碼。
x = df.groupby(['year', 'month', 'class'])['class'].count()
x
最終是一個Series
。 那么我執行以下操作以獲得DataFrame
。
df = pd.DataFrame(x)
這讓我非常接近。 數據最終如下所示。
clazz year month clazz 2015 1 1 2 2 1 15 2 2 45
但是當我做一個條形圖df.plot.bar()
,我只看到一個系列。 所需的輸出只是一個系列,從 2015-01 到 2019-12, class
1 class
每月發生多少次? 然后是另一個系列,從 2015-01 到 2019-12, class
2 class
每月發生多少次?
關於如何以這種方式操縱數據的任何想法?
groupby
- unstack
應該可以解決問題:
數據
df = pd.DataFrame([[2015, 1, 1],
[2015, 1, 1],
[2015, 1, 2],
[2015, 1, 2],
[2015, 1, 2],
[2015, 2, 1],
[2015, 2, 1],
[2015, 2, 1],
[2015, 2, 2],
[2015, 2, 2]], columns = ['year', 'month', 'class'])
解決方案
df_gb = df.groupby(['year', 'month', 'class']).size().unstack(level=2)
輸出
df_gb.plot(kind = 'bar')
我們也可以使用DataFrame.pivot_table
:
df.pivot_table(index=['year','month'],columns='class',aggfunc='size').plot(kind='bar')
或者
df.pivot_table(index='class',columns=['year','month'],aggfunc='size').plot(kind='bar')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.