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
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.
naive.py
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)
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.