Python Central HubSign in

Data Analytics with Python / Phase 3: Data Manipulation with Pandas

Sorting and Ranking

Sort Series and DataFrames by index or by value with sort_index and sort_values, control missing-value placement, and assign ranks with rank.

Two different questions: sort vs rank

  • Sorting rearranges rows so they appear in order.
  • Ranking assigns each value a position number (1st, 2nd, 3rd...) without rearranging anything — the rank becomes a new column or Series aligned to the original order.

Both are everyday analytics needs: sorting a leaderboard, ranking students by score.

Sorting by index: sort_index

Python
import pandas as pd
import numpy as np
 
obj = pd.Series([4, 7, -3, 2, np.nan], index=["d", "a", "c", "b", "e"])
print(obj.sort_index())  # sorted lexicographically by label

Sorting by value: sort_values

Python
print(obj.sort_values())

Missing values sort to the end by default. Use na_position="first" to flip that:

Python
print(obj.sort_values(na_position="first"))

Sorting a DataFrame by one or more columns

Python
frame = pd.DataFrame({"b": [4, 7, -3, 2], "a": [0, 1, 0, 1]})
 
print(frame.sort_values("b"))          # single column
print(frame.sort_values(["a", "b"]))   # tie-break: sort by "a" first, then "b"

Ranking: rank()

rank() assigns each value a position from 1 through the number of valid points, starting at the lowest value. Ties are handled by averaging their ranks by default:

Python
s = pd.Series([7, -5, 7, 4, 2, 0, 4])
print(s.rank())

Both 7s tie for ranks 6 and 7, so they each get the average, 6.5. Other tie-break rules are available via method:

Python
print(s.rank(method="first"))  # ties broken by order of appearance
print(s.rank(method="min"))    # ties get the lowest rank in the group
print(s.rank(ascending=False)) # rank from highest to lowest instead
methodWhat it does
"average"Default — tied values share the mean rank
"min"Tied values all get the lowest rank in the group
"max"Tied values all get the highest rank in the group
"first"Ties broken by the order values appear in the data
"dense"Like "min", but ranks always increase by exactly 1 between groups

Common pitfalls

  • sort_values() on a Series with NaN puts them last — easy to miss if you don't scroll to the bottom of a big result.
  • rank()'s default "average" method can produce fractional ranks (6.5) — if you need whole-number ranks for display, use method="first" or method="dense".
  • Sorting returns a new object; it doesn't sort in place unless you pass inplace=True (and even then, prefer reassigning — it's clearer).

Visualize it

diagram Sort vs rank mermaid
sort_values rearranges rows into order; rank keeps the original row order but attaches a position number to each value.
sketch Bars reordering by sort_values p5.js
The faded bars show the original order; the solid bars show the same values after sort_values() rearranges them ascending.

🧪 Try It Yourself

Exercise 1 – Sort a Series by Value

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Put Missing Values First

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Rank Values With Averaged Ties

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Check your understanding

quizCheck yourself
  1. Where do missing values land in obj.sort_values() by default?

    Show answer

    A — At the end — NaN sorts last by default. Use na_position="first" to flip that.

  2. For s = pd.Series([7, -5, 7, 4, 2, 0, 4]), what rank does each 7 get with the default rank()?

    Show answer

    A — 6.5 — The two 7s tie for ranks 6 and 7, and the default method averages tied ranks to 6.5.

  3. For the same Series, what does s.rank(method="min") give each 7?

    Show answer

    A — 6.0 — The min method gives every tied value the lowest rank in its group, which for the 7s is 6.

  4. How does frame.sort_values(["a", "b"]) order rows?

    Show answer

    A — By a first, then by b to break ties — The columns are applied in the order listed, so b only breaks ties in a.

Next

Sorting rearranges rows you already have. Applying Functions (apply, map, applymap) covers transforming the values inside those rows.

Was this page helpful?

Let us know how we did