Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

python - name of column, that contains the max value

I have dataframe that looks like:

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)

but how to get the name of column with max value and write it into _Max instead of value itself?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Here is the boolean mask:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...