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()
How to get the count of sex per category?
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
pd.crosstab(df['category'],df['sex']).plot.bar()
(df.groupby(['sex','category'])['B']
.count().unstack('sex').plot.bar())
pd.pivot_table(df, values = 'B', index = 'category',
columns = 'sex',aggfunc ='count').plot.bar()
import seaborn as sns
sns.countplot(data=df,x='category',hue='sex')
or,
sns.catplot(data=df,kind='count',x='category',hue='sex')
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()
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.