Python | Pandas DataFrame.nsmallest ()

Python Methods and Functions

nsmallest() Pandas nsmallest() is used to get the n smallest values ​​from a data frame or row.

Syntax: DataFrame.nsmallest (n, columns, keep = 'first')

Parameters:
n: int, Number of values ​​to select
columns: Column to check for least values ​​or user can select column while calling too. [For example: data [“age”]. Nsmallest (3) OR data.nsmallest (3, “age”)]
keep: object to set which value to select if duplicates exit ... Options are 'first' or 'last'.

To upload the CSV file you are using, click here.

Example # 1: retrieving at least 5 values ​​
This example extracts at least 5 values ​​and then compares with others, sorted by the sort_values ​​() function. 
NaN values ​​are removed before attempting this method.

Refer to dropna () .

# pandas package import

import pandas as pd

 
# create data frame from CSV file

data = pd.read_csv ( "employees.csv" )

 
# deleting null values ​​

data.dropna (inplace = True )

 
# extract at least 5

least5 = data.nsmallest ( 5 , "Salary" )

 
# display
least5

Exit:

Example # 2: sorting by sort_values ​​()

# import pandas package

im port pandas as pd

 
# create data frame from CSV file

data = pd.read_csv ( "employees.csv" )

 
# remove null values ​​

data. dropna (inplace = True )

 
# ascending sort

data.sort_values ​​( "Salary" , ascending = True , inplace =  True )

 
# displaying the top 5 values ​​
data.head ()

Exit :

As shown in the output image, the values ​​returned by both functions are the same.





Get Solution for free from DataCamp guru