代码之家  ›  专栏  ›  技术社区  ›  Sean

PANDAS:按组获取最大值,并添加列

  •  1
  • Sean  · 技术社区  · 7 年前

    我意识到这是一个非常简单的问题,但令人恼火的是,我无法理解这一点。我想按位置分组,并返回每个不同位置的最大总计值。这很容易。但是,我找不到一种方法,除了将player列包含在生成的数据帧中之外,还将它包括在内。如何创建一个数据框架,其中包括每个位置的最大得分的一个玩家?

    给定的数据帧结果:

    result = pd.DataFrame([
    {'position': 'Top', 'grandtotal': 36.72, 'player': 'Joe'}, 
    {'position': 'Top', 'grandtotal': 101.18, 'player': 'Bill'},
    {'position': 'Middle', 'grandtotal': 33.32, 'player': 'Jim'}, 
    {'position': 'Middle', 'grandtotal': 72.62, 'player': 'Him'}, 
    {'position': 'Bottom', 'grandtotal': 42.61, 'player': 'Tim'}, 
    {'position': 'Bottom', 'grandtotal': 83.98, 'player': 'Slim'},])
    

    我可以用以下方式返回职位和总金额:

    playerframe = result.groupby(['player', 'position']).sum().reset_index()
    

    给我:

    Top         101.18
    
    Middle      72.62
    
    Bottom      83.98
    

    我也需要一个得分最高的球员的名字!看起来应该很简单。我想要:

    Top         Bill    101.18
    
    Middle      Him    72.62
    
    Bottom      Slim    83.98
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   user3483203    7 年前

    loc 具有 groupby idxmax

    df.loc[df.groupby('position')['grandtotal'].idxmax()]
    
       grandtotal player position
    5       83.98   Slim   Bottom
    3       72.62    Him   Middle
    1      101.18   Bill      Top
    
        2
  •  1
  •   user3483203    7 年前

    通过使用 sort_values groupby agg

    result.sort_values('grandtotal').groupby(['position'],as_index=False).agg({'player':'last','grandtotal':'sum'})
    Out[345]: 
      position  grandtotal player
    0   Bottom      126.59   Slim
    1   Middle      105.94    Him
    2      Top      137.90   Bill
    

    根据您的描述,如果每个组只需要最大值行:

    result.sort_values('grandtotal').drop_duplicates(['position'],keep='last')
    Out[347]: 
       grandtotal player position
    3       72.62    Him   Middle
    5       83.98   Slim   Bottom
    1      101.18   Bill      Top