Skip to content Skip to sidebar Skip to footer

How To Do I Groupby, Count And Then Plot A Bar Chart In Pandas?

I have a Pandas dataframe that looks like the following. year month class ---- ----- ----- 2015 1 1 2015 1 1 2015 1 2 2015 1 2 ... I want to be able t

Solution 1:

A groupby-unstack should do the trick:

Data

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'])

Solution

df_gb = df.groupby(['year', 'month', 'class']).size().unstack(level=2)

Output

df_gb.plot(kind = 'bar')

enter image description here

Solution 2:

We can also use DataFrame.pivot_table:

df.pivot_table(index=['year','month'],columns='class',aggfunc='size').plot(kind='bar')

enter image description here


or

df.pivot_table(index='class',columns=['year','month'],aggfunc='size').plot(kind='bar')

enter image description here

Post a Comment for "How To Do I Groupby, Count And Then Plot A Bar Chart In Pandas?"