python - 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 中:
- df
- 专栏
这是我没有函数的尝试:它可以工作,但商是在外部计算的,是否可以在 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
解决方案
使用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
推荐阅读
- python - Azure Blob 存储错误无法解析 Spark 中的日期
- javascript - 如何仅过滤每种类型的项目?
- wildfly - 适配器-elytron-install-offline.cli 不存在
- php - 循环混合字母和数字以具有 3 个字符串
- amazon-ec2 - AWS Elastic Beanstalk 给出连接问题 - 说意外关闭了连接
- javascript - 页脚未正确呈现
- postgresql - 带有postgress错误的Spring引导DeleteAll
- python - 他们向我显示错误“所有数组必须具有相同的长度”
- .net - 即使在登录时,邮件中的外部链接也会将我发送到登录页面
- flutter - Flutter 页面浏览导航