python - Groupby 返回最大值的整行发生

标签 python pandas

如何获取groupby结果的整行数据?

df
   a   b   c  d   e
0  a  25  12  1  20
1  a  15   1  1   1
2  b  12   1  1   1
3  n  25   2  3   3

In [4]: df = pd.read_clipboard()

In [5]: df.groupby('a')['b'].max()
Out[5]: 
a
a    25
b    12
n    25
Name: b, dtype: int64

如何获取整行?

a   b   c  d   e
a  25  12  1  20
b  12   1  1   1
n  25   2  3   3

我尝试过滤,但 df[df.e == df.groupby('a')['b'].max()] 但大小不同 :(

原始数据:

0          1       2        3     4        5     6      7       8    9   
EVE00101  Trial  DRY RUN  PASS  1610071  1610071  Y  20140808  NaN  29   

10        11                12           13                 14  
FF1  ./ff1.sh  Event Validation  Hive Tables  2015-11-30 9:40:34 

Groupby([1,7])[14].max() 给了我结果,但是在分组系列中作为 1 和 7 作为索引我想要相应的列。 15000行数据,提供1行样本

最佳答案

你可以使用 argmax() :

In [287]: df.groupby('a', as_index=False).apply(lambda x: x.loc[x.b.argmax(),])
Out[287]:
   a   b   c  d   e
0  a  25  12  1  20
1  b  12   1  1   1
2  n  25   2  3   3

即使 b 不是最大的,这种方式也能正常工作。

关于python - Groupby 返回最大值的整行发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34221863/

相关文章:

python - tensorflow 错误: Consider casting elements to a supported type

Python3 - 如何在 pygame 混音器中更改声音的音量

python - 如何将具有自定义 keras 层(.h5)的 keras 模型卡住为 tensorflow 图(.pb)?

python - Python Pandas 中的日期时间 strptime : what's wrong?

python - 复制并转换 Pandas 数据框中的所有值

python - Pandas percentrank 基于每个索引中的组

python - 删除列之间的多余空格

Python 在 Mac 上崩溃

python - 监视数据的 TCP/IP 连接

不进行统计的 Pandas 重采样