2017-06-03 98 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謹慎地闡述您的評論? –