Highest n number of elements.
Returns series of n largest values sorted in descending order.
Options
n: Returns n number of values. Default is 5
keep : Default is 'first', other values are 'last' & 'all'. How to handle duplicate values
Examples using options
We will use n=2 and return series based on MATH column.
import pandas as pd
my_dict={'NAME':['Ravi','Raju','Alex','Ron','King','Jack'],
'ID':[1,2,3,4,5,6],
'MATH':[80,40,70,70,70,30],
'CLASS1':['Four','Three','Three','Four','Five','Three']}
my_data = pd.DataFrame(data=my_dict)
df=my_data.nlargest(columns='MATH',n=2)
print(df)
Output
NAME ID MATH CLASS1
0 Ravi 1 80 Four
2 Alex 3 70 Three
keep
Let us set the value ss keep='first' , you can see there are three equal values in MATH column 2nd in the order.
import pandas as pd
my_dict={'NAME':['Ravi','Raju','Alex','Ron','King','Jack'],
'ID':[1,2,3,4,5,6],
'MATH':[80,40,70,70,70,30],
'CLASS1':['Four','Three','Three','Four','Five','Three']}
my_data = pd.DataFrame(data=my_dict)
df=my_data.nlargest(columns='MATH',n=2,keep='first')
print(df)
Output ( The first one among three equal records are selected with value=70)
NAME ID MATH CLASS1
0 Ravi 1 80 Four
2 Alex 3 70 Three
Now we will change the value as keep='last'
df=my_data.nlargest(columns='MATH',n=2,keep='last')
Output ( The last one among three equal records are selected with value=70 )
NAME ID MATH CLASS1
0 Ravi 1 80 Four
4 King 5 70 Five
Now we will change the value as keep='all'
df=my_data.nlargest(columns='MATH',n=2,keep='all')
Output ( All the three equal values are selected with value = 70 )
NAME ID MATH CLASS1
0 Ravi 1 80 Four
2 Alex 3 70 Three
3 Ron 4 70 Four
4 King 5 70 Five
« Pandas
« Pandas DataFrame
sort_values
groupby
cut
← Subscribe to our YouTube Channel here