【问题标题】:Python: remove rows with max value in each groupPython:删除每组中具有最大值的行
【发布时间】:2018-12-19 17:42:07
【问题描述】:

我有一个这样的熊猫数据框df

In [1]: df
Out[1]:
      country     count
0       Japan        78
1       Japan        80
2         USA        45
3      France        34
4      France        90
5          UK        45
6          UK        34
7       China        32
8       China        87
9      Russia        20
10      Russia        67

我想删除每组中具有最大值的行。所以结果应该是这样的:

      country     count
0       Japan        78
3      France        34
6          UK        34
7       China        32
9      Russia        20

我的第一次尝试:

idx = df.groupby(['country'], sort=False).max()['count'].index
df_new = df.drop(list(idx))

我的第二次尝试:

idx = df.groupby(['country'])['count'].transform(max).index
df_new = df.drop(list(idx))

但它没有用。有什么想法吗?

【问题讨论】:

    标签: python pandas dataframe indexing pandas-groupby


    【解决方案1】:

    groupby/transform('max')

    您可以先按组计算一系列最大值。然后过滤掉 count 等于该系列的实例。请注意,这也会删除重复的最大值。

    g = df.groupby(['country'])['count'].transform('max')
    df = df[~(df['count'] == g)]
    

    g 系列表示每行按组的最大值。如果这等于 df['count'](按索引),则您有一行,其中您的组有最大值。然后,您使用~ 作为否定条件。

    print(df.groupby(['country'])['count'].transform('max'))
    
    0    80
    1    80
    2    45
    3    90
    4    90
    5    45
    6    45
    7    87
    8    87
    9    20
    Name: count, dtype: int64
    

    排序 + 删除

    或者,您可以排序并删除最后的匹配项:

    res = df.sort_values('count')
    res = res.drop(res.groupby('country').tail(1).index)
    
    print(res)
    
      country  count
    9  Russia     20
    7   China     32
    3  France     34
    6      UK     34
    0   Japan     78
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 2021-04-10
      • 2013-04-05
      • 2014-01-22
      • 2022-11-29
      • 1970-01-01
      相关资源
      最近更新 更多