返回与行中最大值相对应的列标题

DPd*_*Pdl 5 python max dataframe pandas

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

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
Run Code Online (Sandbox Code Playgroud)

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

686 is5
950 is5
1005 is5, im5
1005 is5
1180 is5
Run Code Online (Sandbox Code Playgroud)

jo9*_*o9k 3

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

1 is5
2 is5
3 is5
4 is5
5 is5
Run Code Online (Sandbox Code Playgroud)

要创建新列“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)