Sorting and Ranking
Sort by Multiple Keys
Build (cat, score, name) tuples from each record and sort them with Python's
tuple comparison, which compares left-to-right. With pandas, passing a list of
column names to sort_values sorts hierarchically — primary key first,
secondary key as a tiebreaker.
By hand
With pandas
df.sort_values(['cat', 'score']) sorts by cat first, using score to
break ties within each category. The snapshot shows all three columns in their
final sorted order.
naive.py
# trace: ignore records
records = [
{'name': 'al', 'cat': 'B', 'score': 80},
{'name': 'bo', 'cat': 'A', 'score': 55},
{'name': 'cy', 'cat': 'B', 'score': 70},
{'name': 'di', 'cat': 'A', 'score': 90},
]
pairs = []
for r in records:
pairs.append((r['cat'], r['score'], r['name']))
pairs.sort()
result = [p[2] for p in pairs]
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
records = [
{'name': 'al', 'cat': 'B', 'score': 80},
{'name': 'bo', 'cat': 'A', 'score': 55},
{'name': 'cy', 'cat': 'B', 'score': 70},
{'name': 'di', 'cat': 'A', 'score': 90},
]
df = pd.DataFrame(records)
sorted_df = df.sort_values(['cat', 'score'])
print('cats:', sorted_df['cat'].tolist())
print('scores:', sorted_df['score'].tolist())
print('names:', sorted_df['name'].tolist())
print('RESULT:', sorted_df['name'].tolist())
cats: ['A', 'A', 'B', 'B']
scores: [55, 90, 70, 80]
names: ['bo', 'di', 'cy', 'al']
RESULT: ['bo', 'di', 'cy', 'al']
Implementation notes
- The list of column names is sorted hierarchically left-to-right: first column is primary, second is the tiebreaker, and so on. This mirrors how Python tuple comparison works — the naive half uses the same rule explicitly.
- Control direction per column with a matching list:
df.sort_values(['cat', 'score'], ascending=[True, False])sorts categories ascending but scores descending within each category. sort_valuesdefaults tokind='quicksort', which is not guaranteed stable. Passkind='stable'(orkind='mergesort') to preserve the original relative order of rows with equal keys, matching Python'slist.sort()guarantee.- Cross-reference:
sort-two-keys(python-data-basics) for the pure-Python tuple-sort version.