name of column, that contains the max value

后端 未结 1 1287
终归单人心
终归单人心 2021-01-24 17:02

I have dataframe that looks like:

Alice          Eleonora    Mike     Helen
   2               7          8       6                 
   11              5                 


        
相关标签:
1条回答
  • 2021-01-24 17:32

    You can use apply with a lambda to return the name of the column, here we compare the value row-wise against the max, this produces a boolean mask we can use to mask the columns:

    In [229]:
    df['MAX'] = df.apply( lambda x: df.columns[x == x.max()][0], axis=1)
    df
    
    Out[229]:
       Alice  Eleonora  Mike  Helen       MAX
    0      2         7     8      6      Mike
    1     11         5     9      4     Alice
    2      6        15    12      3  Eleonora
    3      5         3     7      8     Helen
    

    Here is the boolean mask:

    In [232]:
    df.apply( lambda x: x == x.max(), axis=1)
    
    Out[232]:
       Alice Eleonora   Mike  Helen
    0  False    False   True  False
    1   True    False  False  False
    2  False     True  False  False
    3  False    False  False   True
    
    0 讨论(0)
提交回复
热议问题