【问题标题】:Calculating grouped by % based on if there are contained values in numerator and unique column value in denominator根据分子中是否包含值和分母中的唯一列值计算按百分比分组
【发布时间】:2020-12-10 06:34:09
【问题描述】:

我正在尝试计算一个比率或百分比,它采用按列(服务列)分组的出现次数,该列至少具有两个可能值(食品或饮料)之一,然后将其除以唯一的数量df 中的列(业务列)值但遇到问题。

原始df:

Rep      | Business | Service
Cindy    Shakeshake    Food
Cindy    Shakeshake    Outdoor
Kim      BurgerKing    Beverage
Kim      Burgerking    Phone
Kim      Burgerking    Car
Nate     Tacohouse     Food
Nate     Tacohouse     Car
Tim      Cofeeshop     Coffee
Tim      Coffeeshop    Seating
Cindy    Italia        Seating
Cindy    Italia        Coffee



 Desired Output:
  Rep    | %
  Cindy    .5
  Kim       1
  Nate      1
  Tim       0

其中 % 是 cindy 拥有至少 1 个食品或饮料行的企业数量除以她 df 中的所有唯一企业。

我正在尝试以下方法:

     (df.assign(Service=df.Service.isin(['Food','Beverage']).astype(int))
       .groupby('Rep')
       .agg({'Business':'nunique','Service':'count'}))

s['Service']/s['Business']

但这并没有给我我正在寻找的东西,因为在这种情况下,服务只为 cindy 提供了 df 中的所有行 4 并且 Businees 列没有给我一个准确的 # 她在哪里有食物或饮料按业务分组。

感谢您提前查看并提供可能的帮助。

【问题讨论】:

    标签: python python-3.x pandas data-science


    【解决方案1】:

    您在此处的代码中犯了一个小错误:

    s=(df.assign(Service=df.Service.isin(['Food','Beverage']).astype(int))
           .groupby('Rep')
           .agg({'Business':'nunique','Service':'count'}))
    
    s['Service']/s['Business']
    

    您需要将'Service':'count' 更改为'Service':'sum'count 只计算每个 Rep 拥有的行数。使用 sum,它计算每个 Rep 拥有的食品或饮料服务的行数。

    【讨论】:

    • 感谢您的反馈,但这仍然给了我错误的输出,因为我希望我的分母只是每个代表拥有的唯一数量的企业,而不是那些只有食物或饮料的企业
    【解决方案2】:

    我认为你需要聚合 sum 来计算匹配值:

    df1 = (df.assign(Service=df.Service.isin(['Food','Beverage']).astype(int))
           .groupby('Rep')
           .agg({'Business':'nunique','Service':'sum'}))
    print (df1)
           Business  Service
    Rep                     
    Cindy         2        1
    Kim           2        1
    Nate          1        1
    Tim           2        0
    
    s = df1['Service']/df1['Business']
    print (s)
    Cindy    0.5
    Kim      0.5
    Nate     1.0
    Tim      0.0
    dtype: float64
    

    【讨论】:

      猜你喜欢
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      相关资源
      最近更新 更多