+

Python | Pandas Series.nlargest ()

The Pandas Series.nlargest() function returns the n largest item from the underlying data in this series object.

Syntax: Series.nlargest (n = 5, keep = `first`)

Parameter:
n: Return this many descending sorted values.
keep: {`first`, `last`, `all`}, default `first`

Returns: Series

Example # 1: Use the Series.nlargest () function to return the first n largest element from a given object series.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ 10 , 25 , 3 , 11 , 24 , 6 ])

  
# Create index

index_ = [ ` Coca Cola` , `Sprite` , ` Coke` , `Fanta` , ` Dew` , `ThumbsUp` ]

 
# set index

sr.index = index_

 
# Print series

print (sr)

Output:

Now we will use the Series.nlargest () function to find the first 2 largest values ​​in a given series object.

# return the first 2 of the largest
# element

result = sr .nlarges t (n = 2 )

 
# Print result

print (result)

Output:


As we see in the output , the Series.nlargest () function successfully returned the first 2 largest values ​​in the given series object.

Example # 2: Use the Series function .nlargest () to return the first n largest element of the given series object.

# import pandas as pd

import pandas as pd

  
# Create series

sr = pd.Series ([ 11 , 21 , 8 , 18 , 65 , 84 , 32 , 10 , 5 , 24 , 32 ])

 
# Print series

print (sr)

 

Output:

Now we will use the Series.nlargest () function to find the first 5 largest values ​​in the given the series object.

# return the top 5 largest
# element

result = sr.nlargest (n = 5 )

  
# Print result

print (result)

Exit :

As we can see in the output, the Series.nlargest () function successfully returned the first 5 largest values ​​in this series object.

Get Solution for free from DataCamp guru