【问题标题】:How to find the index of the 2nd (or 3rd) largest value of a column in a df (Python)?如何在 df (Python) 中找到列的第二个(或第三个)最大值的索引?
【发布时间】:2022-12-20 09:08:01
【问题描述】:

我想找到每列的第二大值,但想收集可以找到该值的位置(简而言之:使用 .nlargest(2).values[-1] 时 .idxmax 的等价物是什么?)

这是我获得第二和第三最高值的推理:

test_2ndmax = pd.DataFrame({'Col{}'.format(i):np.random.randint(0,100,5) for i in range(5)})
display(test_2ndmax)

#retrieving 2nd higest value for each column
display(test_2ndmax.apply(lambda col: col.nlargest(2).values[-1],axis=0))

#retrieving to get 3rd higest value
display(test_2ndmax.apply(lambda col: col.nlargest(3).values[-1],axis=0))

输出是这样的:

    Col0    Col1    Col2    Col3    Col4
0   9       15      24      45      85
1   26      50      91      34      60
2   3       88      84      17      53
3   8       58      73      56      11
4   82      65      93      3       46

Col0    82
Col1    65
Col2    91
Col3    45
Col4    60
dtype: int32

Col0    26
Col1    58
Col2    84
Col3    34
Col4    53
dtype: int32

但是,我想得到这个,因为我会使用 idxmax 的等价物:(例如 col.nlargest(2).values[-1]),

Col0 4
Col1 4
Col2 1
Col3 0
Col4 1

谢谢!

【问题讨论】:

    标签: python sorting max data-cleaning


    【解决方案1】:

    要获得第二大值的索引,请使用.nlargest(2) + .idxmin()(类似于第三大...):

    x = test_2ndmax.apply(lambda col: col.nlargest(2).idxmin(), axis=0)
    print(x)
    

    印刷:

    Col0    3
    Col1    3
    Col2    4
    Col3    4
    Col4    1
    dtype: int64
    

    使用的数据框:

       Col0  Col1  Col2  Col3  Col4
    0    64    10     6    49    94
    1     4    22    86    79    82
    2    84    92    25     1    43
    3    87    41    18    51    29
    4    96    40    73    70    74
    

    【讨论】:

      猜你喜欢
      • 2018-05-20
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 2012-12-30
      • 2013-03-28
      相关资源
      最近更新 更多