【问题标题】:Return top N largest values per group using pandas使用熊猫返回每组前 N 个最大值
【发布时间】:2019-10-21 11:03:03
【问题描述】:

我正在尝试查找系列数的最大值,每个系列按提取它的列的名称分组。

我有一个这样的数据框:

MASTER      SLAVE       Value

Master_1    Slave_1     657879
Master_1    Slave_2     34343
Master_1    Slave_3     453313

Master_2    Slave_1     56667
Master_2    Slave_2     6879
Master_2    Slave_3     12333
Master_2    Slave_4     789
Master_2    Slave_5     22235

Master_3    Slave_1     65765
Master_3    Slave_2     23431
Master_3    Slave_3     445
Master_3    Slave_4     567

我需要找到每个 master 的前两个 slave 的最大值。

到目前为止,我已经得到了:

df.groupby('MASTER')['SLAVE'].unique()

它为每个'MASTER'输出系列'Slaves'值:

Master_1    [657879, 34343, 453313]
Master_2    [56667, 6879, 12333, 789, 22235]
Master_3    [65765, 23431, 445, 789, 567]

但我无法理解在此输入之后我正在处理的数据类型。以及如何对这些值进行排序。

【问题讨论】:

    标签: python pandas dataframe group-by


    【解决方案1】:

    IIUC,一个选项是sort_valuesGroupBy.head,n=2:

    df.sort_values('Value', ascending=False).groupby('MASTER', sort=False).head(2)
    
         MASTER    SLAVE   Value
    0  Master_1  Slave_1  657879
    2  Master_1  Slave_3  453313
    8  Master_3  Slave_1   65765
    3  Master_2  Slave_1   56667
    9  Master_3  Slave_2   23431
    7  Master_2  Slave_5   22235
    

    另一个是使用set_indexGroupBy.nlargest,n=2:

    df.set_index('SLAVE').groupby('MASTER')['Value'].nlargest(2).reset_index()
    
         MASTER    SLAVE   Value
    0  Master_1  Slave_1  657879
    1  Master_1  Slave_3  453313
    2  Master_2  Slave_1   56667
    3  Master_2  Slave_5   22235
    4  Master_3  Slave_1   65765
    5  Master_3  Slave_2   23431
    

    【讨论】:

      【解决方案2】:

      您可以结合使用 sort 和 groupby:

      df.sort_values(['MASTER', 'Value'], ascending=[True, False], inplace=True)
      grp = df.groupby('MASTER')['SLAVE'].indices
      slaves = {k: df.loc[k][:2]['SLAVE'].values  for k in grp.keys()}
      

      将输出:

      {'Master_1': array(['Slave_1', 'Slave_3'], dtype=object),
       'Master_2': array(['Slave_1', 'Slave_5'], dtype=object),
       'Master_3': array(['Slave_1', 'Slave_2'], dtype=object)}
      

      【讨论】:

        猜你喜欢
        • 2019-01-16
        • 1970-01-01
        • 2021-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-12
        相关资源
        最近更新 更多