【发布时间】: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 中:
- 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
【问题讨论】: