【问题标题】:Calculate percentage of categorical column using conditional groupby and count in Python使用条件 groupby 计算分类列的百分比并在 Python 中计数
【发布时间】:2020-12-03 06:44:27
【问题描述】:

我想为每个 id 计算来自 id 的所有行的 True 值的百分比。

这是我的数据示例:

id     col1    
 1     True
 1     True
 1     False
 1     True
 2     False
 2     False

新列应如下所示:

id     col1    num_true
 1     True     0.75
 1     True     0.75
 1     False    0.75
 1     True     0.75
 2     False    0
 2     False    0

这是我尝试做的:

df['num_true']= df[df['col1'] == 'True'].groupby('id')['col1'].count()
df['num_col1_id']= df.groupby('id')['col1'].transform('count')

df['perc_true']= df.num_true/df.num_col1_id

【问题讨论】:

    标签: python pandas group-by


    【解决方案1】:

    groupby 并申请transform 以获取mean

    df['num_true']=df.groupby('id').col1.transform('mean')
    
    
    
      id   col1  num_true
    0   1   True      0.75
    1   1   True      0.75
    2   1  False      0.75
    3   1   True      0.75
    4   2  False      0.00
    5   2  False      0.00
    

    【讨论】:

      【解决方案2】:

      这里是询问的代码:

      import pandas as pd
      df = pd.DataFrame({"col1": [True,True,False,True,False,False]}, index = [1,1,1,1,2,2])
      grouped_df = df.groupby(df.index)
      df["num_true"] = grouped_df.sum() / grouped_df.count()
      

      我在这里所做的是按索引对数据框进行分组, 之后,我将“真”值的数量相加,然后除以值的总数。

      结果:

          col1    num_true
      1   True    0.75
      1   True    0.75
      1   False   0.75
      1   True    0.75
      2   False   0.00
      2   False   0.00
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-21
        • 2021-02-20
        • 2022-06-13
        • 2017-02-15
        • 1970-01-01
        • 2022-06-23
        • 1970-01-01
        • 2019-01-26
        相关资源
        最近更新 更多