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

2024-04-25 11:46:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,看起来像这样:

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

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

^{pr2}$

Tags: 数据dateinccase返回值im1pr2is10
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

可以将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)

相关问题 更多 >