Sorting and Ranking
Sort by Column
Pick the minimum-score row from the remaining pool repeatedly until the pool
is empty, collecting names in order. With pandas, df.sort_values('score')
returns a new DataFrame with all rows in ascending order by that column.
By hand
With pandas
df.sort_values('score') returns a new sorted DataFrame — the original df
is unchanged. The snapshot shows names, scores, and the preserved (non-reset)
original index.
naive.py
# trace: ignore records
records = [
{'name': 'al', 'score': 80},
{'name': 'bo', 'score': 55},
{'name': 'cy', 'score': 90},
{'name': 'di', 'score': 70},
]
scores = [r['score'] for r in records]
names = [r['name'] for r in records]
remaining = list(range(len(records)))
result = []
for _ in range(len(records)):
best = min(remaining, key=lambda i: scores[i])
result.append(names[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)
sorted_df = df.sort_values('score')
print('names:', sorted_df['name'].tolist())
print('scores:', sorted_df['score'].tolist())
print('index:', sorted_df.index.tolist())
print('RESULT:', sorted_df['name'].tolist())
names: ['bo', 'di', 'al', 'cy']
scores: [55, 70, 80, 90]
index: [1, 3, 0, 2]
RESULT: ['bo', 'di', 'al', 'cy']
Implementation notes
sort_valuesreturns a new DataFrame; the original is unchanged. Useinplace=Trueto sort in place, but prefer the default for readable pipelines.- The sorted result keeps the original row index (
[1, 3, 0, 2]above). Add.reset_index(drop=True)to renumber from 0. - Default order is ascending. Pass
ascending=Falsefor descending:df.sort_values('score', ascending=False). - Cross-reference:
sort-by-key(python-data-basics) for the pure-Python version;sort-array(python-numpy ch08) for the NumPy array version.