python - 获取分组中具有最大值的行

标签 python pandas pandas-groupby

<分区>

我有一个根据 id 列分组的数据框。对于每个组,我想获取包含最大值的行(整行,而不仅仅是值)。我可以通过首先获取每个组的最大值,然后创建一个过滤器数组,然后在原始数据帧上应用过滤器来做到这一点。像这样,

import pandas as pd

# Dummy data
df = pd.DataFrame({'id' : [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4],
                   'other_value' : ['a', 'e', 'b', 'b', 'a', 'd', 'b', 'f' ,'a' ,'c', 'e', 'f'],
                   'value' : [1, 3, 5, 2, 5, 6, 2, 4, 6, 1, 7, 3]
                   })

# Get the max value in each group
df_max = df.groupby('id')['value'].max()

# Create row filter
row_filter = [df_max[i]==v for i, v in zip(df['id'], df['value'])]

# Filter
df_target = df[row_filter]
df_target
Out[58]: 
    id other_value  value
2    1           b      5
5    2           d      6
7    3           f      4
10   4           e      7

此解决方案有效,但不知何故似乎过于繁琐。有谁知道更好的方法来做到这一点。最好是oneliner。关于潜在的重复项,我稍后会处理这些问题:)

最佳答案

使用DataFrameGroupBy.idxmax如果只需要选择一个最大值:

df = df.loc[df.groupby('id')['value'].idxmax()]
print (df)
    id other_value  value
2    1           b      5
5    2           d      6
7    3           f      4
10   4           e      7

如果有多个最大值并希望按max 值选择所有行:

df = pd.DataFrame({'id' : [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4],
                   'other_value' : ['a', 'e', 'b', 'b', 'a', 'd', 'b', 'f' ,'a' ,'c', 'e', 'f'],
                   'value' : [1, 3, 5, 2, 5, 6, 2, 4, 6, 1, 7, 7]
                   })

print (df)
    id other_value  value
0    1           a      1
1    1           e      3
2    1           b      5
3    2           b      2
4    2           a      5
5    2           d      6
6    3           b      2
7    3           f      4
8    4           a      6
9    4           c      1
10   4           e      7
11   4           f      7

df = df[df.groupby('id')['value'].transform('max') == df['value']]
print (df)
    id other_value  value
2    1           b      5
5    2           d      6
7    3           f      4
10   4           e      7
11   4           f      7

关于python - 获取分组中具有最大值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50815893/

相关文章:

python - 在列 * 和 * 索引上使用 groupby 和聚合与 Pandas 数据框

python - 将固定宽度、非定界浮点字符串转换为逗号分隔值

python - GeoPandas 绘图 - 有什么方法可以加快速度吗?

python - 如何使用 pandas 从当前行获取过去 12 个月的产品

python - 如何对组进行排序,使第一行中的数字最大,第二行中的数字最小,第三行中的数字第二大,依此类推

python - 将 groupby 转换为具有新列的单行

python - 如何列出目录的所有文件?

python - python如何查看xampp中的MySQL数据库

python - 强制 Django 使用 32 位 Python

python - 循环遍历数据帧以基于Python中的2个索引返回行