Pandas DataFrame 在 Groupby 两列之后找到最大值并获取计数

新手上路,请多包涵

我有一个数据框 df 如下:

    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 对数据进行分组后。我会得到:

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

现在我想找到每个用户拥有最多的标签。如下:

 userId   tag
3122471  18
1234123   4

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

原文由 weigod 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 691
2 个回答

您可以处理聚合数据。

 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

原文由 Zero 发布,翻译遵循 CC BY-SA 3.0 许可协议

按用户 ID 对原始数据框进行分组

 df.groupby('userId').max()['tag']

或者

 df.groupby('userId', as_index=False)['tag'].max()

请注意,第二个解决方案的速度是原来的两倍

%timeit df.groupby('userId').max()['tag']
# 100 loops, best of 3: 5.69 ms per loop
%timeit df.groupby('userId', as_index=False)['tag'].max()
# 100 loops, best of 3: 2.43 ms per loop

原文由 VinceP 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题