python - Pandas groupby 在多列中获取最大值行

标签 python pandas

寻找在多个列中具有最大值的组的行:

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”组中,我想获取具有 col1col2 最大值的行,在这种情况下,当我对 DataFrame 进行分组时,我想获取uniq_id2 的行,因为它的 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/

相关文章:

python - 使用Python SDK导出数据

python - 在 pytorch 中训练期间 best_state 随模型变化

python - 派生类的类/元类方法装饰器

python - RBG 三元组值如何转换为单值?单个值介于 0 到 255 之间。如何将单个值映射到彩色图像?

python - pandas - 找到多级数据帧的最大值

python - 第一次达到某个数字时递增计数器

用于用户输入的python库

python - python中如果value是key则删除字典的value

python - 用 python 和 pandas 传输和写入 Parquet 得到时间戳错误

python - "Correlation matrix"对于字符串。名义数据的相似度