簡體   English   中英

GROUP BY python 后占總大小的百分比

[英]Percentage from Total size after GROUP BY python

   code_module  final_result

    AAA      Distinction            44
                  Fail              91
                 Pass              487
                Withdrawn          126

這是 Python 代碼的結果

 studentInfo.groupby(['code_module','final_result']).agg({'code_module':[np.size]})
  • 我想從總數中計算每個 final_result 的百分比
  • 數學是 AAA.pass/AAA.total

  • 總數是上述所有數字的總和。

我相信你需要SeriesGroupBy.value_counts和參數normalize

s1 = studentInfo.groupby('code_module')['final_result'].value_counts(normalize=True)
print (s1)
code_module  final_result
AAA          Pass            0.651070
             Withdrawn       0.168449
             Fail            0.121658
             Distinction     0.058824
Name: final_result, dtype: float64

或者將您的使用簡化的解決方案DataFrameGroupBy.sizesum %的第一級MultiIndex

s = studentInfo.groupby(['code_module','final_result']).size()
s2 = s.div(s.sum(level=0), level=0)
print (s2)
code_module  final_result
AAA          Distinction     0.058824
             Fail            0.121658
             Pass            0.651070
             Withdrawn       0.168449
dtype: float64

解決方案之間的區別是value_counts以降序返回輸出Series ,以便第一個元素是最常出現的元素,而size不是。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM