熊猫,计算每组的值?

时间:2021-03-12 08:08:07

标签: python pandas

我正在尝试从 df 转到 df2
我按 review_meta_id, age_bin 分组,然后根据 ctr

计算 sum(click_count)/ sum(impression_count)
In [69]: df
Out[69]:
   review_meta_id  age_month  impression_count  click_count age_bin
0               3          4                10            3       1
1               3         10                 5            2       2
2               3         20                 5            3       3
3               3          8                 9            2       2
4               4          9                 9            5       2

In [70]: df2
Out[70]:
   review_meta_id       ctr  age_bin
0               3  0.300000        1
1               3  0.285714        2
2               3  0.600000        3
3               4  0.555556        2



import pandas as pd

bins = [0, 5, 15, 30]
labels = [1,2,3]

l = [dict(review_meta_id=3, age_month=4, impression_count=10, click_count=3), dict(review_meta_id=3, age_month=10, impression_count=5, click_count=2), dict(review_meta_id=3, age_month=20, impression_count=5, cli\
ck_count=3), dict(review_meta_id=3, age_month=8, impression_count=9, click_count=2), dict(review_meta_id=4, age_month=9, impression_count=9, click_count=5)]

df = pd.DataFrame(l)
df['age_bin'] = pd.cut(df['age_month'], bins=bins, labels=labels)


grouped = df.groupby(['review_meta_id', 'age_bin'])

是否有一种优雅的方式来执行以下操作?

data = []
for name, group in grouped:
    ctr = group['click_count'].sum() / group['impression_count'].sum()
    review_meta_id, age_bin = name
    data.append(dict(review_meta_id=review_meta_id, ctr=ctr, age_bin=age_bin))


df2 = pd.DataFrame(data)

2 个答案:

答案 0 :(得分:1)

您可以先按 sum 聚合哥特列,然后用 DataFrame.pop 划分列以供使用和删除列,最后将 MultiIndex 转换为列,并通过 {{3} 删除缺失值的行}}:

df2 = df.groupby(['review_meta_id', 'age_bin'])[['click_count','impression_count']].sum()
df2['ctr'] = df2.pop('click_count') / df2.pop('impression_count')
df2 = df2.reset_index().dropna()
print (df2)
   review_meta_id age_bin       ctr
0               3       1  0.300000
1               3       2  0.285714
2               3       3  0.600000
4               4       2  0.555556

答案 1 :(得分:0)

您可以在按 'review_meta_id', 'age_bin' 对数据框进行分组后使用 apply 函数来计算 'ctr',结果将是一个 Pandas 系列,以便将其转换为我们使用的数据框reset_index() 并提供name='ctr',Series 值对应的列名。

def divide_two_cols(df_sub):
    return df_sub['click_count'].sum() / float(df_sub['impression_count'].sum())

df2 = df.groupby(['review_meta_id', 'age_bin']).apply(divide_two_cols).reset_index(name='ctr')
new_df