寻找在多个列中具有最大值的组的行:
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
在上面,我按“石斑鱼”列分组。在“a”组中,我想获取具有 col1
和 col2
最大值的行,在这种情况下,当我对 DataFrame 进行分组时,我想获取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
稍后您可以使用 df.drop('row_max', axis=1)
row_max
关于python - Pandas groupby 在多列中获取最大值行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203627/