Pandas groupby 两列并绘制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53997862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas groupby two columns and plot
提问by astro123
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()
我试过:df.groupby(['category','sex'])['category','sex'].count().plot.bar()
How to get the count of sex per category?
如何获得每个类别的性别数?
采纳答案by Poudel
Using groupby+unstack:
使用 groupby+unstack:
df.groupby(['sex','category'])['B'].count().unstack('sex').plot.bar()
Using pivot_table:
使用pivot_table:
pd.pivot_table(df, values = 'B', index = 'category',
columns = 'sex',aggfunc ='count').plot.bar()
Using seaborn:
使用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
输出
回答by Vaishali
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.
编辑:如果您有多个列,则可以使用 groupby、count 和 droplevel。
new_df = df.groupby(['category','sex']).count().unstack()
new_df.columns = new_df.columns.droplevel()
new_df.reset_index().plot.bar()