0

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?

Josef
  • 2,648
  • 5
  • 37
  • 73
  • Does this answer your question? [Find row where values for column is maximal in a pandas DataFrame](https://stackoverflow.com/questions/10202570/find-row-where-values-for-column-is-maximal-in-a-pandas-dataframe) – LoukasPap Mar 23 '21 at 08:07

1 Answers1

1

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
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • I get exception TypeError: reduction operation 'argmax' not allowed for this dtype. Could be this because Values in my test also can contain floating point values? – Josef Mar 23 '21 at 08:08
  • You need to use single column in order to use idxmax(), I have added more details to the answer, you can check – ThePyGuy Mar 23 '21 at 08:23