Sort rows with sort_values and columns with sort_index(axis=1). Add rank columns with rank() for percentiles, competition ranking, or deduplication tie-breaking.
sort_values
import pandas as pd
df = pd.DataFrame({'name': ['C','A','B'], 'score': [90, 85, 90]})
by_score = df.sort_values('score', ascending=False)
print(by_score)
Multi-column sort
df.sort_values(['score', 'name'], ascending=[False, True])
rank methods
rank(method='average')— ties get average rank (default)method='min'— competition ranking (1, 2, 2, 4)pct=True— percentile rank 0–1df.reset_index(drop=True)— clean 0..n-1 index after sort
Important interview questions and answers
- Q: Stable sort?
A: Pandas sort is stable—equal keys preserve original order. - Q: rank vs sort?
A: Sort reorders rows; rank adds numeric position column without reordering.
Self-check
- Sort by two columns with different ascending flags.
- Add a percentile rank column.
Tip: After sort_values, call reset_index(drop=True) for a clean 0..n-1 index.
Interview prep
- Stable sort?
Equal keys preserve original order in Pandas sort.
- rank pct?
Percentile rank 0–1 useful for normalization features.