Josef
Josef

Reputation: 2720

Get max value from dataframe with other information

I have dataframe from which I need to extract max value. Here is the example of DF:

Object PARAMETER VALUE
A Param1 1
B Param2 3
C Param1 5
D Param1 2
E Param3 4

Get max value:

maxval = data['VALUE'][data['PARAMETER'] == 'Param1'].max()
print(maxval)    #  5

This works fine but I would like to also get Object name of extracted max value, so the output should be like:

Object name: C, max value = 5

How to do that?

Upvotes: 0

Views: 569

Answers (1)

ThePyGuy
ThePyGuy

Reputation: 18476

You can use idxmax() it will give you the index for maximum value.

index = data['VALUE'][data['PARAMETER'] == 'Param1'].idxmax()

Now you can use this index to get any columns or the entire row.

data.loc[index, 'Object']

Sample Run:

>>import pandas as pd
>>df = pd.DataFrame({'Object': ['A', 'B','C','D', 'E'], 'PARAMETER': ['Param1', 'Param2', 'Param3', 'Param2', 'Param1'], 'VALUE':[1, 2, 3, 4, 5]})
>>df
  Object PARAMETER  VALUE
0      A    Param1      1
1      B    Param2      2
2      C    Param3      3
3      D    Param2      4
4      E    Param1      5

OUTPUT: The masking:

>>df[df['PARAMETER'] == 'Param1']
  Object PARAMETER  VALUE
0      A    Param1      1
4      E    Param1      5

The idxmax():

>>df[df['PARAMETER'] == 'Param1']['VALUE'].idxmax()
4

From the masking, as you can notice, maximum index is 4, that's what idxmax() yields. Now you can use this index to access any column like this:

>>index = df['VALUE'][df['PARAMETER'] == 'Param1'].idxmax()
>>df.loc[index, 'Object']
'E'

or the entire row:

    >>df.loc[index]
    Object            E
    PARAMETER    Param1
    VALUE             5

Name: 4, dtype: object

Upvotes: 1

Related Questions