包含最大值的列的名称 [英] name of column, that contains the max value
本文介绍了包含最大值的列的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据框看起来像:
Alice Eleonora Mike Helen
2 7 8 6
11 5 9 4
6 15 12 3
5 3 7 8
我要创建一个新列,其中包含每行的列名以及给定行的最大值
I want ot create the new column that containes for each row the name of the column with max value for given row
Alice Eleonora Mike Helen _Max
2 7 8 6 Mike
11 5 9 4 Alice
6 15 12 3 Eleonora
5 3 7 8 Helen
我弄清楚如何获得最大值:
I figure out how to get the max value:
df['_Max']=df[['Alice', 'Eleonora', 'Mike', 'Helen']].max(axis=1)
但是如何获取具有最大值的列的名称并将其写入_Max
而不是值本身?
but how to get the name of column with max value and write it into _Max
instead of value itself?
推荐答案
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
这是布尔掩码:
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
这篇关于包含最大值的列的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文