Pandas groupby two columns and plot

Various Methods of Groupby Plots

Data

import numpy as np
import pandas as pd
df = pd.DataFrame({'category': list('XYZXY'),
                   'sex': list('mfmff'),
                   'ThisColumnIsNotUsed': range(5,10)})
df

category sex ThisColumnIsNotUsed
0   X   m   5
1   Y   f   6
2   Z   m   7
3   X   f   8
4   Y   f   9

Using crosstab

pd.crosstab(df['category'],df['sex']).plot.bar()

Using groupby+unstack:

(df.groupby(['sex','category'])
   .count().unstack('sex').plot.bar())

Using pivot_table:

pd.pivot_table(df,index = 'category',
               columns = 'sex',aggfunc ='count').plot.bar()

Using seaborn:

import seaborn as sns
sns.countplot(data=df,x='category',hue='sex')

or,
sns.catplot(data=df,kind='count',x='category',hue='sex')

output

enter image description here


IIUC,

df.groupby(['category','sex']).B.count().unstack().reset_index()\
.plot.bar(x = 'category', y = ['f', 'm'])

enter image description here

Edit: If you have multiple columns, you can use groupby, count and droplevel.

new_df = df.groupby(['category','sex']).count().unstack()
new_df.columns = new_df.columns.droplevel()
new_df.reset_index().plot.bar()

Tags:

Python

Pandas