简体   繁体   中英

Pandas groupby two columns and plot

I have a dataframe like this:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.DataFrame({'category': list('XYZXY'), 'B': range(5,10),'sex': list('mfmff')})

I want to plot count of sex male or female based on category from column 'category'.

I tried:
df.groupby(['category','sex'])['category','sex'].count().plot.bar()

But this gives: 在此处输入图片说明

How to get the count of sex per category?

Various Methods of Groupby Plots

Data

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

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

Using crosstab

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

Using groupby+unstack:

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

Using pivot_table:

pd.pivot_table(df, values = 'B', 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

在此处输入图片说明

IIUC,

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

在此处输入图片说明

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()

You can also use this

pd.pivot_table(df, values = 'B', index = 'category', columns = 'sex',
               aggfunc = lambda x: len(x)).plot.bar()

which results in exactly the same plot.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM