Python:如何获取具有所属组最大值的行? [英] Python : How can I get Rows which have the max value of the group to which they belong?

查看:430
本文介绍了Python:如何获取具有所属组最大值的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重新提了我的问题.我正在寻找以下问题的解决方案:

I reword my question. I'm searching solution for the following problem:

我有一个dataFrame像

I have a dataFrame like:

   Sp   Mt   Value  count
4  MM2  S4   bg     10
5  MM2  S4   dgd    1
6  MM4  S2   rd     2
7  MM4  S2   cb     8
8  MM4  S2   uyi    8

我的目标是获取每组中等于max的所有行,例如:

My objective is to get ALL the rows where count equal max in each group e.g. :

MM4  S4   bg     10
MM4  S2   cb     8
MM4  S2   uyi    8

我按['Sp','Mt']分组

I group by ['Sp','Mt']

有人知道我该如何在熊猫或python中做到这一点?

Somebody knows how can I do it in pandas or in python?

推荐答案

>>> print d
     Sp  Mt Value  Count
ID                      
4   MM2  S4    bg     10
5   MM2  S4   dgd      1
6   MM4  S2    rd      2
7   MM4  S2    cb      8
8   MM4  S2   uyi      8

>>> d.groupby('Sp').apply(lambda t: t[t.Count==t.Count.max()])
         Sp  Mt Value  Count
Sp  ID                      
MM2 4   MM2  S4    bg     10
MM4 7   MM4  S2    cb      8
    8   MM4  S2   uyi      8

这篇关于Python:如何获取具有所属组最大值的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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