【问题标题】:Pandas Groupby - Calculate percentage of values per group total valuePandas Groupby - 计算每组总价值的百分比
【发布时间】:2019-08-18 16:22:37
【问题描述】:

我有这个 Pandas 分组声明:

df['teams'].groupby(train_sub['outcome']).value_counts()

返回类似这样的内容:

outcome | teams 
--------|----------------|-----
  win   | Man utd        | 120
        | Chelsea        | 75
        | Arsenal        | 10
--------|----------------|------
  loss  | Man utd        | 30
        | Chelsea        | 75
        | Arsenal        | 150

对于每个团队,我想显示每个结果占团队总数的百分比(而不是数据框中的总条目)。所以是这样的:

outcome | teams 
--------|----------------|-----
  win   | Man utd        | 0.80
        | Chelsea        | 0.5
        | Arsenal        | 0.0625
--------|----------------|------
  loss  | Man utd        | 0.20
        | Chelsea        | 0.5
        | Arsenal        | 0.9375

请问我如何得到这个结果?

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    像你一样复制数据集:

    df = pd.DataFrame()
    df['outcome'] = ['win', 'win', 'win', 'loss', 'loss', 'loss']
    df['teams'] = ['manu', 'chelsea', 'arsenal', 'manu', 'chelsea', 'arsenal']
    df['points'] = [120, 75, 10, 30, 75, 150]
    grouped = df.groupby(['outcome', 'teams'])['points'].sum()
    

    我的 grouped 变量现在看起来像你的了。

                     points
    outcome teams          
    loss    arsenal     150
            chelsea      75
            manu         30
    win     arsenal      10
            chelsea      75
            manu        120
    


    解决办法:

    grouped 在您的情况下是df['teams'].groupby(train_sub['outcome']).value_counts() 的结果。所以,就这样吧:

    grouped / grouped.groupby(level = 1).sum()
    

    输出:

    outcome teams    points     
    loss    arsenal  0.9375
            chelsea  0.5000
            manu     0.2000
    win     arsenal  0.0625
            chelsea  0.5000
            manu     0.8000
    

    【讨论】:

    • 太棒了,谢谢@ankur 如果我希望整个输出保持原样但只有点列按每个类别的降序排序。
    • 是的,那么我怎样才能看到按最高百分比排序的胜负呢
    • 你可以先做:x = (grouped / grouped.groupby(level = 1).sum()).reset_index(),再做:x.sort_values(['outcome', 'points'], ascending = [False, False])
    猜你喜欢
    • 2022-06-13
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多