← Data analysis with Python

Sorting and top N

Rank rows, find the top few, and count how often each value appears.

Start this lesson

sort_values("col") orders rows from smallest to largest; add ascending=False for largest first. Then .head(3) keeps the top three, which answers "top N" questions in one line. nlargest(3, "col") is a shortcut for the same thing. For category columns, value_counts() counts how many rows have each value and sorts the counts from most to least, like the dictionary counting you wrote by hand earlier.

import io
import pandas as pd

csv_text = """name,group,math,reading,hours
Amara,A,88,92,6
Ben,A,72,80,3
Chen,B,95,85,8
Dalia,B,64,70,2
Emeka,A,79,88,5
Fatima,B,91,94,7
Gus,A,58,65,1
Hana,B,83,77,5
"""
scores = pd.read_csv(io.StringIO(csv_text))
ranked = scores.sort_values("math", ascending=False)
print(ranked[["name", "math"]].head(3))
print(scores.nlargest(3, "reading")[["name", "reading"]])
print(scores["group"].value_counts())

The top three in math are Chen, Fatima and Amara. nlargest finds the top three readers directly. value_counts shows 4 students in each group.

You can sort by two columns: sort_values(["group", "math"]) sorts by group, then by math inside each group.

Sorting returns a new DataFrame; the original stays in its old order unless you assign the result back.