我尝试对groupby操作的结果段/分区应用一个函数。
def get_click_rate(data):
click_count = data[data['event'] == 'click'].shape[0]
view_count = data[data['event'] == 'pageview'].shape[0]
return click_count / view_count
data.groupby('linkid').apply(get_click_rate).reset_index(name='click rate')
这里的想法是,我将 Dataframe 按网页的LinkID
进行分组,然后将每个分区传递给一个函数,该函数过滤子 Dataframe ,计算一个数字并返回它。然而,它返回错误的数字。下面是返回正确数字的代码片段
click_event = data[data['event'] == 'click'].groupby('linkid')['event'].count().reset_index(name='click count')
view_event = data[data['event'] == 'pageview'].groupby('linkid')['event'].count().reset_index(name='view count')
merged_df = pd.merge(left=click_event, right=view_event, on='linkid', how='inner')
merged_df['click rate'] = merged_df['click count'] / merged_df['view count']
至少在我看来,他们在做同样的事情,但顺序不同,第二个片段首先过滤数据,分组,然后合并子 Dataframe ,以达到所需的数字。
有人能告诉我我错过了什么吗?
1条答案
按热度按时间c6ubokkw1#
我在这里尝试了
get_click_rate
函数,它返回的结果似乎与您编写的第二种方法相同。我遇到的唯一问题是,当您试图计算没有'pageview'
事件的linkid
组的点击率时。因此,我对get_click_rate
函数做了一些小修改:测试
get_click_rate
函数输出: