index and column for the max value in pandas dataframe

后端 未结 1 1178
逝去的感伤
逝去的感伤 2021-01-21 06:50

I have a python dataframe df with five columns and five rows. I would like to get the row and column name of the max three values

Example:

df = 

  A            


        
1条回答
  •  抹茶落季
    2021-01-21 07:31

    You could use unstack before sorting:

    >>> df
        A   B   C   D   E   F
    1   0   1   2   3   4   5
    2   6   7   8   9  10  11
    3  12  13  14  15  16  17
    4  18  19  20  21  22  23
    5  24  25  26  27  28  29
    >>> df.unstack()
    A  1     0
       2     6
       3    12
       4    18
       5    24
    B  1     1
       2     7
       3    13
       4    19
       5    25
    [...]
    F  1     5
       2    11
       3    17
       4    23
       5    29
    

    and so

    >>> df2 = df.unstack().copy()
    >>> df2.sort()
    >>> df2[-3:]
    D  5    27
    E  5    28
    F  5    29
    >>> df2[-3:].index
    MultiIndex
    [(D, 5.0), (E, 5.0), (F, 5.0)]
    

    or even

    >>> df.unstack()[df.unstack().argsort()].index[-3:]
    MultiIndex
    [(D, 5.0), (E, 5.0), (F, 5.0)]
    

    [I didn't bother reversing the order: sticking [::-1] at the end should do it.]

    0 讨论(0)
提交回复
热议问题