【问题标题】:Pandas groupby using an equation in agg functionPandas groupby 在 agg 函数中使用方程
【发布时间】:2021-04-25 00:00:21
【问题描述】:

您好,我正在尝试将此数据框用于 groupby 就业,但我想找到每种就业类型的感染率。

如果是感染人数/总人数,感染率应该很容易,但我无法在一行中弄清楚那部分。

我有这个

infect_df = gdf.groupby('employment').agg(rate=('infected' == 1.0 / 'infected':'size')))

如果他们被感染,他们会在数据框中的哪个位置得到 1.0 而不是 0.0,但我知道这不是正确的答案。我只是被感染人数绊倒了。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    由于您的 infected 列已经有 1 和 0,您可以使用 mean 取平均值:

    import pandas as pd
    
    df = pd.DataFrame(
        [('Contractor', 1), ('Contractor', 1), ('Contractor', 0),
         ('Staff', 0), ('Staff', 1), ('Staff', 0),
         ('Custodian', 1), ('Custodian', 1), ('Custodian', 1),
         ('Maintenance', 0), ('Maintenance', 0)],
        columns=['employment', 'infected']
    )
    
    infection_rate = df.groupby('employment')['infected'].mean().reset_index()
    
    # For Display
    print(infection_rate.to_string())
    

    输出:

        employment  infected
    0   Contractor  0.666667
    1    Custodian  1.000000
    2  Maintenance  0.000000
    3        Staff  0.333333
    

    【讨论】:

      【解决方案2】:

      假设你的数据框有两列像这样

      data = StringIO('''
      A,0
      B,0
      A,0
      B,1
      A,1
      A,1
      C,1
      B,1
      C,0
      C,0
      A,0
      B,1
      ''')
      df = pd.read_csv(data,names=['employment','infected'])
      

      你可以通过

      来计算感染率== 1
      df.groupby(['employment'])['infected'].apply(lambda x: (x == 1).sum()/len(x))
      

      【讨论】:

        猜你喜欢
        • 2015-02-10
        • 2020-12-05
        • 1970-01-01
        • 1970-01-01
        • 2019-08-22
        • 2020-12-07
        • 2021-07-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多