pandas取得groupby分組裡最大值所在的行方法

不言
發布: 2023-03-24 14:34:02
原創
3959 人瀏覽過

以下為大家分享一篇pandas取得groupby分組裡最大值所在的行方法,具有很好的參考價值,希望對大家有幫助。一起來看看吧

pandas取得groupby分組裡最大值所在的行方法

如下面這個DataFrame,按照Mt分組,取出Count最大的那行

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
登入後複製


CountMtSpValue0#3s1a1#12s1b225s234##56

##c3
10s2d4
10s2e##5

s3f6


#方法1:在分組中篩選出Count最大的行

#Count#ValueMts103#s1a1s2310s2d10
df.groupby('Mt').apply(lambda t: t[t.Count==t.Count.max()])
登入後複製






Mt
Sp
##44
s2

e5

s3

5

6

s3


f

#6方法2:用transform取得原始dataframe的index,然後過濾出需要的行##
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
登入後複製
CountMt3##a 1310s2s2

#
print df.groupby(['Mt'])['Count'].agg(max)

idx=df.groupby(['Mt'])['Count'].transform(max)
print idx
idx1 = idx == df['Count']
print idx1

df[idx1]
登入後複製
##SpValue0
s1
##d4 410
e

#5

5

6

s3

f

6


#上面的方法都有個問題是3、4行的值都是最大值,這樣回傳了多行,如果只要回傳一行呢? ##MtSpValue03s1a1310#s2#d
方法3:idmax(舊版pandas是argmax)
#
idx = df.groupby('Mt')['Count'].idxmax()
print idx
登入後複製
df.iloc[idx]
Mt
s1 0
s2 3
s3 5
Name: Count, dtype: int64
登入後複製
Count
##4

5


6

s3f
df.iloc[df.groupby(['Mt']).apply(lambda x: x['Count'].idxmax())]
登入後複製
#MtSpValue#031##d
##6
##s1a
310s2##4
5

6

s3

#f

6


##
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)
登入後複製
Mt
s1 1
s2 4
s3 6
dtype: int64
登入後複製
##Mt#0

Value
s1

#1

3

s2

4


#5##s3#
df.sort('Count', ascending=False).groupby('Mt', as_index=False).first()
登入後複製
#MtCount##MtCountSpValue0s1##3 #a

1


1

s210

##d

4

2

s3

6######f######6################################### ###那問題又來了,如果不是要取出最大值所在的行,例如要中間值所在的那行呢? ######思路還是類似,可能具體寫法上要做一些修改,例如方法1和2要修改max演算法,方法3要自己實作一個回index的方法。不管怎樣,groupby之後,每個分組都是一個dataframe。 ######相關推薦:############pandas dataframe實作行列選擇與切片操作############Python 資料處理庫pandas 入門### #####################

以上是pandas取得groupby分組裡最大值所在的行方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!
6
方法4:先排好序,然後每組取第一個