【问题标题】:How to groupby multiple columns and calculate percentage in pandas如何按多列分组并计算熊猫中的百分比
【发布时间】:2018-09-09 18:12:32
【问题描述】:

我在熊猫中有以下数据框

  Date         Code       ID        Quantity
  16-08-2018   156        1         10 
  16-08-2018   156        2         10
  16-08-2018   156        3         10 
  16-08-2018   156        4         10
  17-08-2018   157        1         30
  17-08-2018   157        2         20 
  17-08-2018   157        3         30
  17-08-2018   157        4         20 

我想通过Date and Code 计算 ID 在总数量组中的百分比份额。我想要的数据框是

  Date         Code       ID        Quantity      Perc
  16-08-2018   156        1         10            25
  16-08-2018   156        2         10            25
  16-08-2018   156        3         10            25
  16-08-2018   156        4         10            25
  17-08-2018   157        1         30            30   
  17-08-2018   157        2         20            20
  17-08-2018   157        3         30            30
  17-08-2018   157        4         20            20

如何在熊猫中做到这一点?

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    使用GroupBy + transform'sum'

    g = df.groupby(['Date', 'Code'])['Quantity'].transform('sum')
    df['Perc'] = df['Quantity'] / g * 100
    

    结果:

             Date  Code  ID  Quantity  Perc
    0  16-08-2018   156   1        10    25
    1  16-08-2018   156   2        10    25
    2  16-08-2018   156   3        10    25
    3  16-08-2018   156   4        10    25
    4  17-08-2018   157   1        30    30
    5  17-08-2018   157   2        20    20
    6  17-08-2018   157   3        30    30
    7  17-08-2018   157   4        20    20
    

    【讨论】:

      猜你喜欢
      • 2021-01-05
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      • 2021-11-11
      • 2022-01-21
      • 1970-01-01
      • 2020-09-21
      • 2021-12-19
      相关资源
      最近更新 更多