首页 > 解决方案 > groupby 一列并找到该列和其他列的计数并找到两者的商

问题描述

我正在使用的 df 是:

回复
1 1
2 1
3 0
2 0
1 0
2 1
无效的 1

我想要的输出:

响应计数 count_of_the_rank 反应速度
1 1 2 0.5
2 2 3 0.66
3 0 1 0
无效的 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

标签: pythonpandasdataframe

解决方案


使用groupby然后aggregateresponse_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

推荐阅读