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

 

  Count Mt Sp Value
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()])

 

    Count Mt Sp Value
Mt          
s1 0 3 s1 a 1
s2 3 10 s2 d 4
4 10 s2 e 5
s3 5 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

 

  Count Mt Sp Value
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

 

  Count Mt Sp Value
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())]

 

  Count Mt Sp Value
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

 

  Mt Value
0 s1 1
3 s2 4
5 s3 6

 

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

1
df.sort('Count', ascending=False).groupby('Mt', as_index=False).first()

 

  Mt Count Sp Value
0 s1 3 a 1
1 s2 10 d 4
2 s3 6 f 6


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM