查找跨多列具有最大值的组的行:
pd.DataFrame([{'grouper': 'a', 'col1': 1, 'col2': 3, 'uniq_id': 1}, {'grouper': 'a', 'col1': 2, 'col2': 4, 'uniq_id': 2}, {'grouper': 'a', 'col1': 3, 'col2': 2, 'uniq_id': 3}])
col1 col2 grouper uniq_id
0 1 3 a 1
1 2 4 a 2
2 3 2 a 3
在上面,我是按"grouper“列分组的。在"a“组中,我希望获得col1
和col2
的最大值,在本例中,当我对DataFrame进行分组时,我希望获得uniq_id
为2
的行,因为它具有最高值col1/col2和4,因此结果将是:
col1 col2 grouper uniq_id
1 2 4 a 2
在我的实际示例中,我使用的是时间戳,所以我实际上并不期望平局。但是在平局的情况下,我并不关心我在组中选择了哪一行,所以在这种情况下它只是组的first
。
发布于 2019-05-18 23:58:59
还有一种你可以尝试的方法:
# find row wise max value
df['row_max'] = df[['col1','col2']].max(axis=1)
# filter rows from groups
df.loc[df.groupby('grouper')['row_max'].idxmax()]
col1 col2 grouper uniq_id row_max
1 2 4 a 2 4
稍后,您可以使用df.drop('row_max', axis=1)
删除row_max
发布于 2019-05-18 23:50:47
使用transform
的IIUC然后与原始数据帧进行比较
g=df.groupby('grouper')
s1=g.col1.transform('max')
s2=g.col2.transform('max')
s=pd.concat([s1,s2],axis=1).max(1)
df.loc[df[['col1','col2']].eq(s,0).any(1)]
Out[89]:
col1 col2 grouper uniq_id
1 2 4 a 2
发布于 2019-05-19 00:19:48
有趣的方法随处可见。添加另一个只是为了展示apply
(我是它的铁杆粉丝)的威力,并使用一些其他提到的方法。
import pandas as pd
df = pd.DataFrame(
[
{"grouper": "a", "col1": 1, "col2": 3, "uniq_id": 1},
{"grouper": "a", "col1": 2, "col2": 4, "uniq_id": 2},
{"grouper": "a", "col1": 3, "col2": 2, "uniq_id": 3},
]
)
def find_max(grp):
# find max value per row, then find index of row with max val
max_row_idx = grp[["col1", "col2"]].max(axis=1).idxmax()
return grp.loc[max_row_idx]
df.groupby("grouper").apply(find_max)
https://stackoverflow.com/questions/56203627
复制相似问题