2017-06-03 179 views
0

我有一个数据框,其中包含'A','B','C','D'列值......这只是一些种类的分组。我想生成列值与其计数的直方图。Seaborn Distplot和Barplot

import seaborn as sns 
sns.distplot(dfGroupingWithoutNan['patient_group']) 

这产生了一个错误:

TypeError: unsupported operand type(s) for /: 'str' and 'int' 

我想,也许是因为我不是熟悉distplot,我不使用它的正确方法。我在想,我可以通过一个系列,它将能够确定每个值的计数,并将其显示在相应的直方图中。

无论如何,我想到了其他解决方案,这就是我想出的。

series1 = dfGroupingWithoutNan['patient_group'].value_counts() 
dfPatientGroup = pd.DataFrame({'levels' : series1.index, 'level_values' : series1.values}) 

sns.set_style("whitegrid") 
sns.barplot(x="levels", y="level_values", data=dfPatientGroup) 

这次我能够通过使用条形图来产生每个值与其数量的关系图。

我只是想问一下,有没有其他的方式来做到这一点,比如如果我使用distplot它会如何工作?另外,我是否真的需要创建一个新的数据框才能拥有某种存储值和数量的存储库?我在想,不可能让distplot自动确定计数而不需要经历创建新数据帧的麻烦?

回答

0

我会用Counter来做到这一点。逻辑非常相似,你在做什么,但你并不需要创建一个额外的数据帧:

from collections import Counter 
cnt = Counter(dfGroupingWithoutNan.patient_group) 
sns.barplot(x=cnt.keys(), y=cnt.values()) 

我不知道任何解决方案,在seabornmatplotlib直方图自动处理字符串值。

+1

只需要执行'df ['patient_group']。value_counts()' –

+0

@PaulH谨慎地阐述您的评论? –