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

5

我有一个数据框,长这样:

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
2个回答

3
你可以使用 idxmax 函数并设置参数 axis=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)


1
在我看来, idxmax(1) 是在行中查找最大元素的最惯用方法,再加上1。 - MaxU - stand with Ukraine

1
您可以尝试以下方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接