Sorting and Ranking
nLargest Top Rows
Pick the top-N values from a pool by repeated max-pick, shrinking the pool
each round. With pandas, nlargest(n, col) returns the top-N rows in
descending order without sorting the entire DataFrame.
By hand
Keep a remaining pool of indices. Each of 3 iterations picks the index of
the current maximum score, appends that score to result, and removes the
index from the pool.
naive.py
Replay: real traced execution (multi-file project)
scores = [80, 55, 90, 70]
remaining = list(range(len(scores)))
result = []
for _ in range(3):
best = max(remaining, key=lambda i: scores[i])
result.append(scores[best])
remaining.remove(best)
print('RESULT:', result)
scores ← [80, 55, 90, 70]
1scores = [80, 55, 90, 70]2remaining = list(range(len(scores)))values this step[80, 55, 90, 70]scoresremaining ← [0, 1, 2, 3]
1scores = [80, 55, 90, 70]2remaining = list(range(len(scores)))3result = []values this step[0, 1, 2, 3]remainingresult ← []
2remaining = list(range(len(scores)))3result = []4for _ in range(3):values this step[]result_ ← 0
3result = []4for _ in range(3):5 best = max(remaining, key=lambda i: scores[i])values this step0_best ← 2
4for _ in range(3):5 best = max(remaining, key=lambda i: scores[i])6 result.append(scores[best])values this step2bestresult ← [90]
5best = max(remaining, key=lambda i: scores[i])6result.append(scores[best])7remaining.remove(best)values this step[] → [90]resultremaining ← [0, 1, 3]
6 result.append(scores[best])7 remaining.remove(best)8print('RESULT:', result)values this step[0, 1, 2, 3] → [0, 1, 3]remaining_ ← 1
3result = []4for _ in range(3):5 best = max(remaining, key=lambda i: scores[i])values this step0 → 1_best ← 0
4for _ in range(3):5 best = max(remaining, key=lambda i: scores[i])6 result.append(scores[best])values this step2 → 0bestresult ← [90, 80]
5best = max(remaining, key=lambda i: scores[i])6result.append(scores[best])7remaining.remove(best)values this step[90] → [90, 80]resultremaining ← [1, 3]
6 result.append(scores[best])7 remaining.remove(best)8print('RESULT:', result)values this step[0, 1, 3] → [1, 3]remaining_ ← 2
3result = []4for _ in range(3):5 best = max(remaining, key=lambda i: scores[i])values this step1 → 2_best ← 3
4for _ in range(3):5 best = max(remaining, key=lambda i: scores[i])6 result.append(scores[best])values this step0 → 3bestresult ← [90, 80, 70]
5best = max(remaining, key=lambda i: scores[i])6result.append(scores[best])7remaining.remove(best)values this step[90, 80] → [90, 80, 70]resultremaining ← [1]
6 result.append(scores[best])7 remaining.remove(best)8print('RESULT:', result)values this step[1, 3] → [1]remainingfor _ in range(3):
3result = []4for _ in range(3):5 best = max(remaining, key=lambda i: scores[i])stdout ← RESULT: [90, 80, 70]
7 remaining.remove(best)8print('RESULT:', result)values this stepRESULT: [90, 80, 70]stdout
With pandas
df.nlargest(3, 'score') returns a new DataFrame with the 3 highest-scoring
rows in descending order. The snapshot shows that the original row index is
preserved ([2, 0, 3]), just like sort_values.
library.py
import pandas as pd
from dalib.display import set_display
set_display()
records = [
{'name': 'al', 'score': 80},
{'name': 'bo', 'score': 55},
{'name': 'cy', 'score': 90},
{'name': 'di', 'score': 70},
]
df = pd.DataFrame(records)
top3 = df.nlargest(3, 'score')
print('names:', top3['name'].tolist())
print('scores:', top3['score'].tolist())
print('index:', top3.index.tolist())
print('RESULT:', top3['score'].tolist())
names: ['cy', 'al', 'di']
scores: [90, 80, 70]
index: [2, 0, 3]
RESULT: [90, 80, 70]
Implementation notes
nlargest(n, col)is more efficient thansort_values(col, ascending=False).head(n)for large DataFrames — it uses a partial selection algorithm that avoids fully ordering the DataFrame.- Use
nsmallest(n, col)for the bottom-N rows. - The result preserves the original row index. Add
.reset_index(drop=True)to renumber from 0. - Cross-reference:
top-k-select(python-data-basics) for the pure-Python heapq version;sort-by-column(this chapter) for full-sort comparison.