Monday 18 December 2023

Pandas: nsmallest: Get n smallest values in a DataFrame

Using ‘nsmallest’ method, we can get n smallest 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 youngest employees.

three_younger_emps = df.nsmallest(3, columns='Age')

 

‘three_younger_emps’ point to below data set.

       Name  Age       City Gender  Rating
2     Joel   29  Hyderabad   Male      67
0  Krishna   34  Bangalore   Male      91
5      Raj   34    Chennai   Male      89

Example 2: Get three youngest employees by their rating also.

three_younger_emps_by_rating = df.nsmallest(3, columns=['Age', 'Rating'])

‘three_younger_emps_by_rating’ point to below data set.

       Name  Age       City Gender  Rating
2     Joel   29  Hyderabad   Male      67
5      Raj   34    Chennai   Male      89
0  Krishna   34  Bangalore   Male      91

Find the below working application.

 

n_smallest_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_younger_emps = df.nsmallest(3, columns='Age')
print('\nthree_younger_emps : \n', three_younger_emps)

three_younger_emps_by_rating = df.nsmallest(3, columns=['Age', 'Rating'])
print('\nthree_younger_emps_by_rating : \n', three_younger_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_younger_emps : 
       Name  Age       City Gender  Rating
2     Joel   29  Hyderabad   Male      67
0  Krishna   34  Bangalore   Male      91
5      Raj   34    Chennai   Male      89

three_younger_emps_by_rating : 
       Name  Age       City Gender  Rating
2     Joel   29  Hyderabad   Male      67
5      Raj   34    Chennai   Male      89
0  Krishna   34  Bangalore   Male      91



Previous                                                 Next                                                 Home

No comments:

Post a Comment