我有一个示例数据框:
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)
如何添加另外三个条形来显示基于整个数据集的每种类型的平均值-> test.groupby('type')['type'].count()/(len(test))*100
将感谢您的帮助!
答案 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')