Quantcast
Channel: Pandas groupby two columns and plot - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by BhishanPoudel for Pandas groupby two columns and plot

$
0
0

Various Methods of Groupby Plots

Data

import numpy as npimport pandas as pddf = pd.DataFrame({'category': list('XYZXY'),'sex': list('mfmff'),'ThisColumnIsNotUsed': range(5,10)})dfcategory sex ThisColumnIsNotUsed0   X   m   51   Y   f   62   Z   m   73   X   f   84   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 snssns.countplot(data=df,x='category',hue='sex')or,sns.catplot(data=df,kind='count',x='category',hue='sex')

output

enter image description here


Viewing all articles
Browse latest Browse all 4

Trending Articles