在应用pandas groupby之后将条形图添加到图以显示平均值

时间:2018-11-23 18:44:50

标签: python pandas seaborn pandas-groupby

我有一个示例数据框:

test = pd.DataFrame({'cluster':['1','1','1','1','2','2','2','2','2','3','3','3'],
                 'type':['a','b','c','a','a','b','c','c','a','b','c','a']})

然后我使用groupby绘制每个集群的类型值的百分比:

pct_col = test.groupby(['cluster','type'])['type'].count()/(test.groupby('cluster').size())*100 # don't reset the index!
test = test.set_index(['cluster', 'type']) # make the same index here
test['count %'] = pct_col
test = test.reset_index() # to take the hierarchical index off again
sns.catplot(x="cluster", y="count %", hue="type", kind="bar", data=test)

enter image description here

如何添加另外三个条形来显示基于整个数据集的每种类型的平均值-> test.groupby('type')['type'].count()/(len(test))*100

将感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

使用crosstab

pd.crosstab(test.cluster,test.type,normalize='index',margins=True)
Out[305]: 
type            a         b         c
cluster                              
1        0.500000  0.250000  0.250000
2        0.400000  0.200000  0.400000
3        0.333333  0.333333  0.333333
All      0.416667  0.250000  0.333333

#pd.crosstab(test.cluster,test.type,normalize='index',margins=True).mul(100).stack()

更新我认为使用pandas

很容易
pd.crosstab(test.cluster,test.type,normalize='index',margins=True).plot(kind='bar')

enter image description here