网络编程
位置:首页>> 网络编程>> Python编程>> pandas获取groupby分组里最大值所在的行方法

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

作者:Tobin's Blog  发布时间:2021-08-14 21:39:14 

标签: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


CountMtSpValue
03s1a1
12s1b2
25s2c3
310s2d4
410s2e5
56s3f6

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


df.groupby('Mt').apply(lambda t: t[t.Count==t.Count.max()])



CountMtSpValue
Mt




s103s1a1
s2310s2d4
410s2e5
s356s3f6

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


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

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

df[idx1]

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
03s1a1
310s2d4
410s2e5
56s3f6

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

方法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


CountMtSpValue
03s1a1
310s2d4
56s3f6


df.iloc[df.groupby(['Mt']).apply(lambda x: x['Count'].idxmax())]


CountMtSpValue
03s1a1
310s2d4
56s3f6


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


MtValue
0s11
3s24
5s36

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


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


MtCountSpValue
0s13a1
1s210d4
2s36f6

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

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

来源: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/

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com