1. 程式人生 > 實用技巧 >pandas取各組中的最大值

pandas取各組中的最大值

import pandas as pd 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]}) 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最大的行

1 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 2 3 4 5 6 7 8 print df.groupby(['Mt'])['Count'].agg(max) idx=df.groupby(['Mt'])['Count'].transform(max) print idx idx1 = idx == df['Count'] print idx1 df[idx1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Mt s1 3 s2 10 s3 6 Name: Count, dtype: int64 0 3 1 3 2 10 3 10 4 10 5 6 dtype: int64 0 True 1 False 2 False 3 True 4 True 5 True 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 2 idx = df.groupby('Mt')['Count'].idxmax() print idx
1 2 3 4 5 6 df.iloc[idx] Mt s1 0 s2 3 s3 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())]

CountMtSpValue
0 3 s1 a 1
3 10 s2 d 4
5 6 s3 f 6

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

MtValue
0 s1 1
3 s2 4
5 s3 6

方法4:先排好序,然後每組取第一個

1 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