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
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.