select row with maximum and minimum value in python pandas

In this tutorial we will learn how to select row with maximum and minimum value in python pandas

  • Get the entire row which has the maximum value of a column in python pandas
  • Get the entire row which has the minimum value of a column in python pandas.

Let’s see example of both

Create dataframe:

import pandas as pd
import numpy as np

#Create a DataFrame
d = {
    'Name':['Alisa','Bobby','jodha','jack','raghu','Cathrine',
            'Alisa','Bobby','kumar','Alisa','Alex','Cathrine'],
    'Age':[26,24,23,22,23,24,26,24,22,23,24,24],
     
       'Score':[85,63,55,74,31,77,85,63,42,62,89,77]}

df = pd.DataFrame(d,columns=['Name','Age','Score'])
df

So the resultant dataframe will be

get row with maximum and minimum value in python pandas1

 

Get the entire row which has the maximum value in python pandas:

So let’s extract the entire row where score is maximum i.e. get all the details of student with maximum score as shown below


# get the row of max value
df.loc[df['Score'].idxmax()]

Explanation:

df[‘Score’].idxmax() – > returns the index of the row where column name “Score” has maximum value.

df.loc[] -> returns the row of that index

so the output will be

get row with maximum and minimum value in python pandas 2

 

Get the entire row which has the minimum value in python pandas:

So let’s extract the entire row where score is minimum i.e. get all the details of student with minimum score as shown below


# get the row of minimum value
df.loc[df['Score'].idxmin()]

so the output will be

get row with maximum and minimum value in python pandas 3

 

 

previous-small Get entire row with maximum and minimum value in python pandas                                                                                                          next_small Get entire row with maximum and minimum value in python pandas

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts