【问题标题】:groupby a column and find the count of this column and other column and find the quotient of the twogroupby 一列并找到该列和其他列的计数并找到两者的商
【发布时间】:2021-04-21 20:48:53
【问题描述】:

我正在使用的 df 是:

rank response
1 1
2 1
3 0
2 0
1 0
2 1
null 1

我想要的输出:

rank response_count count_of_the_rank response_rate
1 1 2 0.5
2 2 3 0.66
3 0 1 0
null 1 1 1

响应率计算为 response_count/count_of_the_rank

我想要一个函数来生成这个数据框并存储在给定的 csv 中:

  1. df
  2. 栏目

这是我没有函数的尝试: 它有效,但商是在外部计算的,是否可以在 agg 内部进行? 也没有csv

rank_df = df.groupby(['rank']).agg(
    count_of_the_rank=('rank', 'count'),
    response_count=('response', 'sum'))
rank_df['group_target_rate'] = rank_df['response_count']/rank_df['count_of_the_rank']

这是尝试使用一个函数,但它不起作用:

def target_rate_analysis(df, column):
    new_df = df.groupby([column]).agg(
        response_count=('response', 'sum'),
        'count_of_the' + column=(column, 'count'),
        response_count=('response', 'mean'))
    return new_df

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用groupby,然后使用aggregate(对于response_rate,您可以使用"mean"):

    df_out = df.groupby("rank", as_index=False).agg(
        response_count=("response", "sum"),
        count_of_the_rank=("response", "size"),
        response_rate=("response", "mean"),
    )
    print(df_out)
    

    打印:

       rank  response_count  count_of_the_rank  response_rate
    0     1               1                  2       0.500000
    1     2               2                  3       0.666667
    2     3               0                  1       0.000000
    

    编辑:作为一个函数:

    def analysis(df, column):
        return df.groupby("rank", as_index=False).agg(
            **{
                "{}_count".format(column): (column, "sum"),
                "{}_count_of_the_rank".format(column): (column, "size"),
                "{}_rate".format(column): (column, "mean"),
            }
        )
    
    
    print(analysis(df, "response"))
    

    打印:

       rank  response_count  response_count_of_the_rank  response_rate
    0     1               1                           2       0.500000
    1     2               2                           3       0.666667
    2     3               0                           1       0.000000
    

    【讨论】:

    • 谢谢!有可能把它变成一个函数吗?就像如果我传递一个列列表并且对于每个单独的列,我将为该列生成一个 csv
    • 我知道你的编辑!谢谢你! :)
    • 嗨,如果我们将 null 作为一个类别怎么办?我们如何获得作为一个组的空值计数?我现在看到它显示为响应计数量为 0
    猜你喜欢
    • 2020-07-11
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    相关资源
    最近更新 更多