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

yipeiwu_com5年前Python基础

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

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最大的行

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,然后过滤出需要的行

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

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)

idx = df.groupby('Mt')['Count'].idxmax()
print idx
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

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

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 Value
0 s1 1
3 s2 4
5 s3 6

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

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分组里最大值所在的行方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python使用import导入本地脚本及导入模块的技巧总结

本文实例讲述了Python使用import导入本地脚本及导入模块的技巧。分享给大家供大家参考,具体如下: 导入本地脚本 import 如果你要导入的 Python 脚本与当前脚本位于同一...

python 重定向获取真实url的方法

楼主在做公司项目的时候遇到url重定向的问题,因此上网简单查找,作出如下结果 由于使用的是语言是python所以以下是python的简单解决方案 http_headers = { '...

python 实现矩阵填充0的例子

需求: 原矩阵 [[1 2 3] [4 5 6] [7 8 9]] 在原矩阵元素之间填充元素 0,得到 [[1. 0. 2. 0. 3.] [0. 0. 0. 0. 0....

python实现生命游戏的示例代码(Game of Life)

生命游戏的算法就不多解释了,百度一下介绍随处可见。 因为网上大多数版本都是基于pygame,matlab等外部库实现的,二维数组大多是用numpy,使用起来学习成本比较高,所以闲暇之余...

pyqt5 QProgressBar清空进度条的实例

在停止和开始进度条的同时,将进度条清空的动作也是常常需要用到的。 具体用法如下: self.progressBar = QProgressBar(self) self.progres...