TExcelTAD
Home › pandas › Sorting and Ranking

Sorting and Ranking

Sorting brings the interesting rows to the top: the best-selling products, the latest orders, the slowest servers. pandas sorts by column values with sort_values(), by labels with sort_index(), and can pick the top or bottom rows directly with nlargest()/nsmallest().

sort_values()

python · try it yourself
import pandas as pd

runners = pd.DataFrame({
    "runner": ["Ama", "Bao", "Cleo", "Dov", "Eko", "Finn"],
    "club": ["North", "South", "North", "East", "South", "East"],
    "time_min": [41.5, 38.2, 44.0, 38.2, 47.3, 40.1],
})
print(runners.sort_values("time_min"))
print(runners.sort_values("time_min", ascending=False).head(2))
  runner   club  time_min
1    Bao  South      38.2
3    Dov   East      38.2
5   Finn   East      40.1
0    Ama  North      41.5
2   Cleo  North      44.0
4    Eko  South      47.3
  runner   club  time_min
4    Eko  South      47.3
2   Cleo  North      44.0

Sorting returns a new DataFrame; the original row labels travel with their rows, which is why the index looks shuffled.

Sorting by several columns

Pass a list of columns, and optionally a list of directions. Ties in the first column are broken by the second:

python · try it yourself
import pandas as pd

runners = pd.DataFrame({
    "runner": ["Ama", "Bao", "Cleo", "Dov", "Eko", "Finn"],
    "club": ["North", "South", "North", "East", "South", "East"],
    "time_min": [41.5, 38.2, 44.0, 38.2, 47.3, 40.1],
})
print(runners.sort_values(["club", "time_min"]))
print(runners.sort_values(["time_min", "runner"], ascending=[True, False]))
  runner   club  time_min
3    Dov   East      38.2
5   Finn   East      40.1
0    Ama  North      41.5
2   Cleo  North      44.0
1    Bao  South      38.2
4    Eko  South      47.3
  runner   club  time_min
3    Dov   East      38.2
1    Bao  South      38.2
5   Finn   East      40.1
0    Ama  North      41.5
2   Cleo  North      44.0
4    Eko  South      47.3

In the second result Bao and Dov have the same time, so the reversed name order puts Dov first.

Missing values and custom keys

Missing values go last by default (na_position="first" changes that). The key argument transforms values before comparing, for example to sort text case-insensitively:

python · try it yourself
import numpy as np
import pandas as pd

files = pd.DataFrame({
    "name": ["report.pdf", "Agenda.docx", "budget.xlsx", "Zoo.png"],
    "size_kb": [420, np.nan, 88, 1310],
})
print(files.sort_values("name"))
print(files.sort_values("name", key=lambda s: s.str.lower()))
print(files.sort_values("size_kb", na_position="first"))
          name  size_kb
1  Agenda.docx      NaN
3      Zoo.png   1310.0
2  budget.xlsx     88.0
0   report.pdf    420.0
          name  size_kb
1  Agenda.docx      NaN
2  budget.xlsx     88.0
0   report.pdf    420.0
3      Zoo.png   1310.0
          name  size_kb
1  Agenda.docx      NaN
2  budget.xlsx     88.0
0   report.pdf    420.0
3      Zoo.png   1310.0

Plain sorting puts uppercase letters before lowercase (Z before b), which is rarely what people expect.

sort_index()

python · try it yourself
import pandas as pd

temps = pd.Series({"Wed": 19, "Mon": 17, "Tue": 21})
print(temps.sort_index())
print(temps.sort_values(ascending=False))
Mon    17
Tue    21
Wed    19
dtype: int64
Tue    21
Wed    19
Mon    17
dtype: int64

nlargest() and nsmallest()

When you only want the top n rows, these are shorter and faster than sorting everything:

python · try it yourself
import pandas as pd

runners = pd.DataFrame({
    "runner": ["Ama", "Bao", "Cleo", "Dov", "Eko", "Finn"],
    "time_min": [41.5, 38.2, 44.0, 38.2, 47.3, 40.1],
})
print(runners.nsmallest(3, "time_min"))
print(runners.nlargest(1, "time_min"))
  runner  time_min
1    Bao      38.2
3    Dov      38.2
5   Finn      40.1
  runner  time_min
4    Eko      47.3

rank()

rank() gives each value its position in the sorted order. The method argument decides what happens with ties:

method= Tied values get
"average" (default) the average of their positions (e.g. 1.5, 1.5)
"min" the lowest position (1, 1, then 3) — like sports rankings
"dense" the lowest position, without gaps (1, 1, then 2)
"first" positions in order of appearance
python · try it yourself
import pandas as pd

runners = pd.DataFrame({
    "runner": ["Ama", "Bao", "Cleo", "Dov", "Eko", "Finn"],
    "time_min": [41.5, 38.2, 44.0, 38.2, 47.3, 40.1],
})
runners["avg"] = runners["time_min"].rank()
runners["min"] = runners["time_min"].rank(method="min").astype(int)
runners["dense"] = runners["time_min"].rank(method="dense").astype(int)
print(runners.sort_values("time_min"))
  runner  time_min  avg  min  dense
1    Bao      38.2  1.5    1      1
3    Dov      38.2  1.5    1      1
5   Finn      40.1  3.0    3      2
0    Ama      41.5  4.0    4      3
2   Cleo      44.0  5.0    5      4
4    Eko      47.3  6.0    6      5

Test yourself

How do you sort a DataFrame by price, highest first?

  1. df.sort("price", desc=True)
  2. df.sort_values("price", ascending=False)
  3. df.sort_index("price")
  4. df.order_by("-price")

Values 10, 20, 20, 30 are ranked with method="min". What rank does 30 get?

  1. 3
  2. 4
  3. 2
  4. 3.5

Which call returns the 5 rows with the highest score?

  1. df.top(5, "score")
  2. df.nlargest(5, "score")
  3. df.head(5)
  4. df.max(5)