Monday 18 December 2023

Pandas: nlargest: Get n largest values in a DataFrame

Using ‘nlargest’ method, we can get n largest values in a DataFrame.

 

I am going to use below data set to demonstrate the examples.

       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      91
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

 

Example 1: Get the three oldest people from the dataset.

three_oldest_emps = df.nlargest(3, columns='Age')

‘three_oldest_emps’ point to below data set.

        Name  Age       City  Gender  Rating
4  Jitendra   52  Bangalore    Male      87
1     Sailu   35  Hyderabad  Female      76
3     Chamu   35    Chennai  Female     100

Example 2: get the three oldest people by their rating from the dataset.

three_oldest_emps_by_rating = df.nlargest(3, columns=['Age', 'Rating'])

‘three_oldest_emps_by_rating’ point to below data set.

        Name  Age       City  Gender  Rating
4  Jitendra   52  Bangalore    Male      87
3     Chamu   35    Chennai  Female     100
1     Sailu   35  Hyderabad  Female      76

Find the below working application.

 

n_largest_rows.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [91, 76, 67, 100, 87, 89]}

df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

three_oldest_emps = df.nlargest(3, columns='Age')
print('\nthree_oldest_emps : \n', three_oldest_emps)

three_oldest_emps_by_rating = df.nlargest(3, columns=['Age', 'Rating'])
print('\nthree_oldest_emps_by_rating : \n', three_oldest_emps_by_rating)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      91
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

three_oldest_emps : 
        Name  Age       City  Gender  Rating
4  Jitendra   52  Bangalore    Male      87
1     Sailu   35  Hyderabad  Female      76
3     Chamu   35    Chennai  Female     100

three_oldest_emps_by_rating : 
        Name  Age       City  Gender  Rating
4  Jitendra   52  Bangalore    Male      87
3     Chamu   35    Chennai  Female     100
1     Sailu   35  Hyderabad  Female      76

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment