Martingale
Martingale

Reputation: 523

Python: Locate the max value of a column and pick up the value of other column in the same row

I have next data frame with two columns:

Idx =[1,2,3,4,5]
Values =[7,-2,-1,10,5]
lists = list(zip(Idx, Values))  
dfsr = pd.DataFrame(lists, columns = ['Idx', 'Values'])
dfsr

This generates the next DataFrame

    Idx Values
0   1   7
1   2   -2
2   3   -1
3   4   10
4   5   5

What I want to do is to locate the max value in the column "values" and select the corresponding value of the column "Idx".

I have tried this:

MVI = dfsr[dfsr.Values == dfsr.Values.max()]
MVI

which leads to:

   Idx  Values
3   4   10

But what I need is just the value of the Idx. The return should be just 4 as a number to use it later.

Can somebody help me with this easy thing please? Thank you very much!

Upvotes: 0

Views: 44

Answers (1)

Georgina Skibinski
Georgina Skibinski

Reputation: 13407

Try:

>>> MVI = dfsr.loc[dfsr.Values == dfsr.Values.max(), 'Idx']
>>> MVI
3    4
Name: Idx, dtype: int64

Alternatively, if you just want the object itself (not pandas.Series object):

>>> MVI = dfsr.loc[dfsr.Values == dfsr.Values.max(), 'Idx'].to_list()[0]
>>> MVI
4

Upvotes: 3

Related Questions