Pandas groupby 两列并绘制 [英] Pandas groupby two columns and plot
本文介绍了Pandas groupby 两列并绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数据框:
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'.
我试过了:df.groupby(['category','sex'])['category','sex'].count().plot.bar()
但这给出了:
如何获取每个类别的性别数?
How to get the count of sex per category?
推荐答案
Groupby Plots 的各种方法
数据
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()
使用 groupby+unstack:
(df.groupby(['sex','category'])['B']
.count().unstack('sex').plot.bar())
使用数据透视表:
pd.pivot_table(df, values = 'B', index = 'category',
columns = 'sex',aggfunc ='count').plot.bar()
使用seaborn:
import seaborn as sns
sns.countplot(data=df,x='category',hue='sex')
or,
sns.catplot(data=df,kind='count',x='category',hue='sex')
输出
这篇关于Pandas groupby 两列并绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文