pandas獲取groupby分組里最大值所在的行方法
如下面這個DataFrame,按照Mt分組,取出Count最大的那行
1
2
3
4
|
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 |
那問題又來了,如果不是要取出最大值所在的行,比如要中間值所在的那行呢?
思路還是類似,可能具體寫法上要做一些修改,比如方法1和2要修改max算法,方法3要自己實現一個返回index的方法。 不管怎樣,groupby之后,每個分組都是一個dataframe。
以上這篇pandas獲取groupby分組里最大值所在的行方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:http://www.guoguoday.com/post/pandas%E8%8E%B7%E5%8F%96groupby%E5%88%86%E7%BB%84%E9%87%8C%E6%9C%80%E5%A4%A7%E5%80%BC%E6%89%80%E5%9C%A8%E7%9A%84%E8%A1%8C/