pandas获取groupby分组里最大值所在的行

https://blog.csdn.net/mappy93/article/details/79319506/

pandas获取groupby分组里最大值所在的行

  

pandas获取groupby分组里最大值所在的行

如下面这个DataFrame,按照Mt分组,取出Count最大的那行

  1.  
    import pandas as pd
  2.  
    df = pd.DataFrame({'Sp':['a','b','c','d','e','f'], 'Mt':['s1', 's1', 's2','s2','s2','s3'], 'Value':[1,2,3,4,5,6], 'Count':[3,2,5,10,10,6]})
  3.  
    df
 CountMtSpValue
0 3 s1 a 1
1 2 s1 b 2
2 5 s2 c 3
3 10 s2 d 4
4 10 s2 e 5
5 6 s3 f 6

方法1:在分组中过滤出Count最大的行

df.groupby('Mt').apply(lambda t: t[t.Count==t.Count.max()])
  CountMtSpValue
Mt     
s10 3 s1 a 1
s23 10 s2 d 4
4 10 s2 e 5
s35 6 s3 f 6

方法2:用transform获取原dataframe的index,然后过滤出需要的行

  1.  
    print df.groupby(['Mt'])['Count'].agg(max)
  2.  
     
  3.  
    idx=df.groupby(['Mt'])['Count'].transform(max)
  4.  
    print idx
  5.  
    idx1 = idx == df['Count']
  6.  
    print idx1
  7.  
     
  8.  
    df[idx1]
  1.  
    Mt
  2.  
    s1 3
  3.  
    s2 10
  4.  
    s3 6
  5.  
    Name: Count, dtype: int64
  6.  
    0 3
  7.  
    1 3
  8.  
    2 10
  9.  
    3 10
  10.  
    4 10
  11.  
    5 6
  12.  
    dtype: int64
  13.  
    0 True
  14.  
    1 False
  15.  
    2 False
  16.  
    3 True
  17.  
    4 True
  18.  
    5 True
  19.  
    dtype: bool
 CountMtSpValue
0 3 s1 a 1
3 10 s2 d 4
4 10 s2 e 5
5 6 s3 f 6

上面的方法都有个问题是3、4行的值都是最大值,这样返回了多行,如果只要返回一行呢?

方法3:idmax(旧版本pandas是argmax)

  1.  
    idx = df.groupby('Mt')['Count'].idxmax()
  2.  
    print idx
  3.  
     
  4.  
    df.iloc[idx]
  1.  
    Mt
  2.  
    s1 0
  3.  
    s2 3
  4.  
    s3 5
  5.  
    Name: Count, dtype: int64
 CountMtSpValue
0 3 s1 a 1
3 10 s2 d 4
5 6 s3 f 6
  1.  
    df.iloc[df.groupby(['Mt']).apply(lambda x: x['Count'].idxmax())]
  2.  
     
 CountMtSpValue
0 3 s1 a 1
3 10 s2 d 4
5 6 s3 f 6
  1.  
    def using_apply(df):
  2.  
    return (df.groupby('Mt').apply(lambda subf: subf['Value'][subf['Count'].idxmax()]))
  3.  
     
  4.  
    def using_idxmax_loc(df):
  5.  
    idx = df.groupby('Mt')['Count'].idxmax()
  6.  
    return df.loc[idx, ['Mt', 'Value']]
  7.  
     
  8.  
    print using_apply(df)
  9.  
     
  10.  
    using_idxmax_loc(df)
  11.  
     
  1.  
    Mt
  2.  
    s1 1
  3.  
    s2 4
  4.  
    s3 6
  5.  
    dtype: int64
 MtValue
0 s1 1
3 s2 4
5 s3 6

方法4:先排好序,然后每组取第一个

df.sort('Count', ascending=False).groupby('Mt', as_index=False).first()
 MtCountSpValue
0 s1 3 a 1
1 s2 10 d 4
2 s3 6 f 6

那问题又来了,如果不是要取出最大值所在的行,比如要中间值所在的那行呢?

思路还是类似,可能具体写法上要做一些修改,比如方法1和2要修改max算法,方法3要自己实现一个返回index的方法。 不管怎样,groupby之后,每个分组都是一个dataframe。

原文地址:https://www.cnblogs.com/gina11/p/14777684.html