pbPassingBI
/
Aggregation & reshaping beginner 5 min

Sorting and ranking

sort_values, nlargest, rank, and ranking within groups.

What you'll be able to do
  • Sort by one or more columns
  • Get the top N efficiently
  • Rank within groups

Sorting

df.sort_values('revenue', ascending=False)
df.sort_values(['region', 'revenue'], ascending=[True, False])
df.sort_values('revenue', na_position='first')

Remember to assign the result — df.sort_values(...) alone changes nothing.

Top N

df.nlargest(10, 'revenue')
df.nsmallest(5, 'revenue')

Faster and clearer than sorting the whole frame and slicing, especially on large data.

Ranking

df['rank'] = df['revenue'].rank(ascending=False)
df['rank'] = df['revenue'].rank(method='dense', ascending=False)
methodBehaviour on ties
averageDefault — ties share the mean rank, e.g. 2.5
minTies get the lowest rank, then skip — like SQL RANK
denseTies share, no skip — like SQL DENSE_RANK
firstBroken by order of appearance — like ROW_NUMBER

The default average producing decimal ranks surprises people coming from SQL.

Ranking within groups

df['rank_in_region'] = (df.groupby('region')['revenue']
                          .rank(method='dense', ascending=False))

top3 = df[df['rank_in_region'] <= 3]

The pandas equivalent of RANK() OVER (PARTITION BY region ORDER BY revenue DESC).

Sorting the index

df.sort_index()
df = df.reset_index(drop=True)   # renumber 0..n after filtering

drop=True discards the old index rather than keeping it as a column — usually what you want after filtering.

Key points
  • nlargest is clearer and faster than sorting then slicing
  • rank() defaults to average, giving decimal ranks on ties
  • groupby().rank() is the equivalent of a SQL windowed rank
Check yourself