【问题标题】:Get the index of n maximum values in a column in dataframe获取数据框中列中 n 个最大值的索引
【发布时间】:2022-06-13 23:58:09
【问题描述】:

我有一个数据框,我想获取每行中 4 个最大值的索引和值。例如,在下面的df中,a列中,10,6,7,8是四个最大值。

import pandas as pd
df = pd.DataFrame()
df['a'] = [10, 2, 3, -1,4,5,6,7,8]
df['id'] = [100, 2, 3, -1,4,5,0,1,2]
df

我想要的输出是:

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    尝试最大,

    df.nlargest(4, 'a').reset_index()
    

    输出:

       index   a   id
    0      0  10  100
    1      8   8    2
    2      7   7    1
    3      6   6    0
    

    【讨论】:

      【解决方案2】:

      您可以对a 列进行排序

      out = (df.sort_values('a', ascending=False).iloc[:4]
             .sort_index(ascending=True)
             .reset_index())
      
      print(out)
      
         index   a   id
      0      0  10  100
      1      6   6    0
      2      7   7    1
      3      8   8    2
      

      【讨论】:

        猜你喜欢
        • 2015-06-12
        • 2013-07-11
        • 1970-01-01
        • 2019-02-17
        • 2011-10-18
        • 2019-09-10
        • 2018-08-04
        • 2017-03-27
        相关资源
        最近更新 更多