【问题标题】:Returning a Column Header which Corresponds to a Maximum Value in a Row返回对应于行中最大值的列标题
【发布时间】:2017-12-04 16:23:20
【问题描述】:

我有一个如下所示的数据框:

case    inc_date    is1     is5     is10    im1     im5     im10
686     6/8/1972    0.141   0.300   0.149   0.134   0.135   0.142
950     6/1/1945    0.160   0.345   0.172   0.088   0.096   0.138
1005    10/16/1945  0.164   0.261   0.151   0.131   0.261   0.133
1005    11/12/1947  0.146   0.310   0.182   0.112   0.129   0.121
1180    10/9/1945   0.159   0.278   0.134   0.141   0.138   0.150

我想找出每行中的最大值并返回值为最大值的列名。例如,对于上面的数据框,它会返回:

686 is5
950 is5
1005 is5, im5
1005 is5
1180 is5

【问题讨论】:

    标签: python pandas dataframe max


    【解决方案1】:

    您可以使用idxmaxaxis=1 来查找每行中值最大的列:

    1 is5
    2 is5
    3 is5
    4 is5
    5 is5
    

    要创建新列“Max”,请使用df['Max'] = df.idxmax(axis=1)

    要查找每列中出现最大值的行索引,请使用df.idxmax()(或等效的df.idxmax(axis=0))。


    对于第二高,您可以使用 df.apply(lambda x: df.index[x.argsort()[::-1][1]], axis=1)

    【讨论】:

    • IMO idxmax(1) - 是查找行中最大元素的最惯用方式 - +1
    【解决方案2】:

    您可以尝试以下方法:

    In [96]: cols = df.columns[df.columns.str.contains('^i[sm]')]
    
    In [97]: cols
    Out[97]: Index(['is1', 'is5', 'is10', 'im1', 'im5', 'im10'], dtype='object')
    
    In [98]: mask = df[cols].eq(df[cols].max(1), axis=0)
    
    In [99]: mask
    Out[99]:
         is1   is5   is10    im1    im5   im10
    0  False  True  False  False  False  False
    1  False  True  False  False  False  False
    2  False  True  False  False   True  False
    3  False  True  False  False  False  False
    4  False  True  False  False  False  False
    
    In [104]: df[['case']].join(mask.apply(lambda r: ', '.join(cols[r]), axis=1).to_frame('idx'))
    Out[104]:
       case       idx
    0   686       is5
    1   950       is5
    2  1005  is5, im5
    3  1005       is5
    4  1180       is5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多