Noob Coder
Noob Coder

Reputation: 233

How to find index of an array which has maximum value in dataframe using python?

I have a dataframe which has array of elements, i would like to get the index value of the maximum number in the array using python,

Desired output:

Elements    Max Value Index

[3,4,5]              2

[2,0,1]              0

I tried using:

df['Max Value Index'] = df["Elements"].apply(lambda x:max(x))

It gives me the maximum value, , I just need the index number, i tried many ways but not able to get that, can anybody please help?

Upvotes: 0

Views: 67

Answers (2)

Nick
Nick

Reputation: 147146

You could use numpy.argmax:

df['Max Value Index'] = df['Elements'].apply(lambda l:np.argmax(l))

Or in straight python:

df['Max Value Index'] = df["Elements"].apply(lambda l:l.index(max(l)))

Output:

    Elements  Max Value Index
0  [3, 4, 5]                2
1  [2, 0, 1]                0

Upvotes: 1

Ravindra S
Ravindra S

Reputation: 6422

Try idxmax(x)

df['Max Value Index'] = df["Elements"].apply(lambda x:idxmax(x))

Upvotes: 1

Related Questions