寻找一组在多列中具有最大值的行:
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
在上面,我按“分组”列进行分组。在“一”小组,我想拥有的最大的行col1
和col2
,在这种情况下,当我组我的数据框,我想获得该行uniq_id
的2
,因为它的COL1 / COL2与4的最高值,因此结果将是:
col1 col2 grouper uniq_id
1 2 4 a 2
在我的实际示例中,我使用的是时间戳记,因此我实际上并不期望联系。但是,如果是平局,我对选择组中的哪一行都不关心,因此first
在这种情况下,它只是该组中的一行。
您可以尝试的另一种方法:
# 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
稍后您可以row_max
使用df.drop('row_max', axis=1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句