2

I've a dataframe that contains normalized values. From each row I can obtain the maxvalue, but now I want to get also the corresponding column names.

For example df:

|----------------------------------------|
|    a    |     b     |   c   | 'newcol' |
|----------------------------------------|
|  0.960  |    1.00   | 1.00  |  b, c    |
|----------------------------------------|
|  0.922  |    0.955  | 0.971 |  c       |
|----------------------------------------|

So i want to create this newcol containing the column names that have the max values. I've tried df.idxmax(axis=1) however this returns only the first column with the max value

Find all indices of maximum in Pandas DataFrame Tries to solve the same problem however the data is stored in a list instead of a new column in same df

1

1 Answer 1

1

Use DataFrame.dot for compare all columns with maximum:

df['newcol'] = df.eq(df.max(axis=1), axis=0).dot(df.columns + ',').str.strip(',')
print (df)
       a      b      c newcol
0  0.960  1.000  1.000    b,c
1  0.922  0.955  0.971      c
Sign up to request clarification or add additional context in comments.

1 Comment

That is working indeed, thanks for the fast response

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.