【问题标题】:How can I pivot a table and get the percentage of each row in Python?如何旋转表格并获取 Python 中每一行的百分比?
【发布时间】:2020-09-15 21:57:36
【问题描述】:

我有一个包含几行的数据框,每一行都是与主要组不同的子组,就像这样:

group    subgroup    count
A        aaa         10
A        bbb         20
A        ccc         30
B        aaa         10
B        bbb         20

如何旋转该表并获取每个子组的百分比? 基本上,我想得到这个:

group    subgroup_aaa    subgroup_bbb    subgroup_ccc
A        0.1666          0.33333         0.5
B        0.3333          0.5             0

【问题讨论】:

    标签: python pandas group-by pivot-table


    【解决方案1】:

    我们可以试试crosstabnormalize

    s=pd.crosstab(index=df.group,columns=df.subgroup,values=df['count'],
                  normalize='index',aggfunc='sum').\
                  add_prefix('subgroup_').reset_index()
    Out[476]: 
    subgroup group  subgroup_aaa  subgroup_bbb  subgroup_ccc
    0            A      0.166667      0.333333           0.5
    1            B      0.333333      0.666667           0.0
    

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多