Given the following code:
# Import pandas library
import pandas as pd
# Data to lists.
data = [{'Student': 'Eric', 'Grade': 96, 'Class':'A'}, \
{'Student': 'Caden', 'Grade': 92, 'Class':'A'}, \
{'Student': 'Sam', 'Grade': 90, 'Class':'A'}, \
{'Student': 'Leon', 'Grade': 88, 'Class':'A'}, \
{'Student': 'Laura', 'Grade': 80, 'Class':'B'}, \
{'Student': 'Leann', 'Grade': 22, 'Class':'B'}, \
{'Student': 'Glen', 'Grade': 9, 'Class':'C'}, \
{'Student': 'Jack', 'Grade': 90, 'Class':'C'}, \
{'Student': 'Jill', 'Grade': 87, 'Class':'C'}, \
{'Student': 'Joe', 'Grade': 58, 'Class':'C'}, \
{'Student': 'Andrew', 'Grade': 48, 'Class':'D'}, \
{'Student': 'Travis', 'Grade': 39, 'Class':'E'}, \
{'Student': 'Henry', 'Grade': 23, 'Class':'E'}, \
{'Student': 'Chris', 'Grade': 19, 'Class':'E'}, \
{'Student': 'Jim', 'Grade': 1, 'Class':'E'}, \
{'Student': 'Sarah', 'Grade': 93, 'Class':'E'}, \
{'Student': 'Brit', 'Grade': 92, 'Class':'E'}, \
]
# Creates DataFrame.
df = pd.DataFrame(data)
print(df.groupby('Class')['Grade'].nlargest(2))
From the dataframe, I would like to return the students' names with the top 2 grades out of each class. I would like to return two different versions of the results.
Version 1 would have all of the original columns:
And, Version 2 would only return the names:
Output (would prefer to have the aforementioned two versions):