简体   繁体   English

熊猫通过多列和最大值分组

[英]Pandas group by with multiple columns and max value

I have some problems with group by with multiple columns and max value. 我有多个列和max group by问题。

A   B   C   D   E   F   G   H

x   q   e   m   k   2   1   y
x   q   e   n   l   5   2   y
x   w   e   b   j   7   3   y
x   w   e   v   h   3   4   y

This query is correct and returning what I want. 此查询是正确的,并返回我想要的。

SELECT A, B, C, D, E, MAX(F) FROM mytable group by A, B, C

Results 结果

 x   q   e   n   l   5
 x   w   e   b   j   7

How it can be achieved in pandas? 如何在大熊猫中实现?

I try this: 我尝试这样:

df.groupby(['A', 'B', 'C'], as_index=False)['F'].max()

And this translates to this: 这就是这样:

SELECT A, B, C, MAX(F) FROM mytable group by A, B, C

This also does not work 这也行不通

df.groupby(['A', 'B', 'C'], as_index=False)['F','D','E'].max()

How can I return also column D, E as it in sql query? 如何在SQL查询中也返回D,E列?

Seems like you need 好像你需要

groups = ['A', 'B', 'C']
selects = ['A', 'B', 'C','D', 'E','F']

df.groupby(groups, as_index=False).apply(lambda s: s.loc[s.F.idxmax(), selects]).reset_index(drop=True)

    A   B   C   D   E   F
0   x   q   e   n   l   5
1   x   w   e   b   j   7

尝试这样的事情:

df.groupby(['A', 'B', 'C'], as_index=False).agg({'D': 'first', 'E': 'last', 'F': 'max'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM