Pandas DataFrame在Groupby两列之后找到最大值并获得计数 [英] Pandas DataFrame find the max after Groupby two columns and get counts

查看:1024
本文介绍了Pandas DataFrame在Groupby两列之后找到最大值并获得计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框df,如下所示:

I have a dataframe df as following:

   userId  pageId  tag
0  3122471  e852   18
1  3122471  f3e2   18
2  3122471  7e93   18
3  3122471  2768    6
4  3122471  53d9    6
5  3122471  06d7   15
6  3122471  e31c   15
7  3122471  c6f3    2
8  1234123  fjwe    1
9  1234123  eiae    4
10 1234123  ieha    4

使用df.groupby(['userId', 'tag'])['pageId'].count()将数据按userId和tag分组之后. 我会得到:

After using df.groupby(['userId', 'tag'])['pageId'].count() to group the data by userId and tag . I will get:

userId   tag
3122471  2      1
         6      2
         15     2
         18     3
1234123   1     1
          4     2

现在,我想查找每个用户拥有最多的标签. 如下所示:

Now I want to find the tag that each user has the most. Just as following:

userId   tag
3122471  18
1234123   4

(注意:如果有多个具有相同计数的标签,我想使用功能my_rule确定要显示的标签)

(Note: if there are multiple tags that has the same count, I want to use a function my_rule to determine which to show)

推荐答案

您可以处理汇总数据.

In [387]: dff = df.groupby(['userId', 'tag'], as_index=False)['pageId'].count()

In [388]: dff
Out[388]:
    userId  tag  pageId
0  1234123    1       1
1  1234123    4       2
2  3122471    2       1
3  3122471    6       2
4  3122471   15       2
5  3122471   18       3

In [389]: dff.groupby('userId').apply(lambda x: x.tag[x.pageId.idxmax()])
Out[389]:
userId
1234123     4
3122471    18
dtype: int64

这篇关于Pandas DataFrame在Groupby两列之后找到最大值并获得计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆