2

I have a data frame that's something like this:

Keyword  A B C D ... X Y Z
First    1 2 3 4 ... 8 5 3
Second   2 6 2 9 ... 6 1 2
Third    3 3 2 3 ... 5 3 4

I've also got a list letters which just has the column names from A to Z.

I want to get the keyword of the maximum value in each column.

If I want to get it for just one column, something like this works:

max = df['A'].max()
df.loc[df['A'] == max, 'Keyword']

A Third

How would I go about getting it for all the columns?

So that would be:

A Third
B Second
C First
D Second
...
X First
Y First
Z Third

1 Answer 1

2

1st set_index then idxmax

df.set_index('Keyword').idxmax()
A     Third
B    Second
C     First
D    Second
X     First
Y     First
Z     Third
dtype: object
Sign up to request clarification or add additional context in comments.

6 Comments

Would this work if I have other columns I don't want considered? Like for example a column Misc between Keyword and A
df.set_index('Keyword').drop(['Columns1','Columns2'],1).idxmax() @Taco
@Taco happy coding :-)
Thanks! Additional question if you don't mind. Let's say the Misc column has a bunch of values from 0 to 1. Now if I only want to consider rows where Misc is between 0.6 and 0.8, how would I go about that?
Thank you, you're a lifesaver! :)
|

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.