tethys4
tethys4

Reputation: 55

Find the column name of the max value of a row in a data frame

I am using a pandas data frame in Python and have 121 columns and 5 rows. I want to find the max value in each row and print the name of the column where it occurs. I really have no idea how I would even begin to do this but I would appreciate the help.

Edit: the column names are strings

Edit: Some example scenario is: enter image description here

and for this example I would want something like:

id: 000621fb3cbb32d8935728e48679680e
breed: african_hunting_dog
confidence: 0.011319

etc for all 3 rows

Upvotes: 0

Views: 1036

Answers (3)

hamish
hamish

Reputation: 1

    for col in df.columns:
       if df[col].values[-1] == df.iloc[-1].max():
          print(col)

or alternatively

    [x if df[x].values[-1] == df.iloc[-1].max() for x in df.columns]

Upvotes: 0

YusufUMS
YusufUMS

Reputation: 1493

You may try this for beginner:

import pandas as pd

df = pd.DataFrame({'Col1':['A','B','C','D','E'], 'Col2': [4,2,6,3,2], 'Col3':[3,6,4,3,1]})
for x in range(len(df)):
    dt = df.iloc[x]
    if dt[1] > dt[2]:
        print ('Col2:{}'.format(dt[1]))
    elif dt[1] < dt[2]:
        print ('Col3:{}'.format(dt[2]))
    else:
        print ('Both cols are same')

Upvotes: 0

BENY
BENY

Reputation: 323376

You can using idxmax and max with axis=1

df.idxmax(axis=1)
df.max(axis=1)

Upvotes: 3

Related Questions