Data analysis with pandas · Lesson 6 of 15

Sorting and ranking

Sort a table by one or more columns, put the biggest values first, get the top rows with nlargest and give every row a rank number.

About 12 minutes · code runs in your browser, nothing to install

Sorting answers questions like "which city is warmest?" or "what sold best?". The examples use the average temperature (°C) and rain (mm) of six cities in one month.

Sort by one column

sort_values("temp") returns a new DataFrame sorted from smallest to largest. Add ascending=False for largest first. The original df does not change, and every row keeps its index label, so you can still see where it came from.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "city": ["Lisbon", "Oslo", "Athens", "Dublin", "Madrid", "Vienna"],
    "country": ["PT", "NO", "GR", "IE", "ES", "AT"],
    "temp": [17, 2, 19, 9, 17, 6],
    "rain": [95, 64, 46, 76, 33, 52],
})

print(df.sort_values("temp"))
print(df.sort_values("temp", ascending=False).head(3))
Output
     city country  temp  rain
1    Oslo      NO     2    64
5  Vienna      AT     6    52
3  Dublin      IE     9    76
0  Lisbon      PT    17    95
4  Madrid      ES    17    33
2  Athens      GR    19    46
     city country  temp  rain
2  Athens      GR    19    46
0  Lisbon      PT    17    95
4  Madrid      ES    17    33

Sort by several columns

Give a list of columns: pandas sorts by the first and uses the next one to break ties. ascending can be a list too, one value per column. Here Lisbon and Madrid have the same temperature, so the drier city comes first.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "city": ["Lisbon", "Oslo", "Athens", "Dublin", "Madrid", "Vienna"],
    "country": ["PT", "NO", "GR", "IE", "ES", "AT"],
    "temp": [17, 2, 19, 9, 17, 6],
    "rain": [95, 64, 46, 76, 33, 52],
})

out = df.sort_values(["temp", "rain"], ascending=[False, True])
print(out)
Output
     city country  temp  rain
2  Athens      GR    19    46
4  Madrid      ES    17    33
0  Lisbon      PT    17    95
3  Dublin      IE     9    76
5  Vienna      AT     6    52
1    Oslo      NO     2    64

After sorting, the index labels are mixed up. reset_index(drop=True) numbers the rows 0, 1, 2 … again and throws away the old labels. sort_index() puts rows back in label order.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "city": ["Lisbon", "Oslo", "Athens", "Dublin", "Madrid", "Vienna"],
    "country": ["PT", "NO", "GR", "IE", "ES", "AT"],
    "temp": [17, 2, 19, 9, 17, 6],
    "rain": [95, 64, 46, 76, 33, 52],
})

top = df.sort_values("rain", ascending=False).reset_index(drop=True)
print(top[["city", "rain"]])
Output
     city  rain
0  Lisbon    95
1  Dublin    76
2    Oslo    64
3  Vienna    52
4  Athens    46
5  Madrid    33

Now the index is the position in the ranking, starting at 0.

Top and bottom rows

nlargest(n, column) and nsmallest(n, column) are short ways to get the top or bottom rows without sorting the whole table yourself.

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "city": ["Lisbon", "Oslo", "Athens", "Dublin", "Madrid", "Vienna"],
    "country": ["PT", "NO", "GR", "IE", "ES", "AT"],
    "temp": [17, 2, 19, 9, 17, 6],
    "rain": [95, 64, 46, 76, 33, 52],
})

print(df.nlargest(2, "rain")[["city", "rain"]])
print(df.nsmallest(2, "temp")[["city", "temp"]])
Output
     city  rain
0  Lisbon    95
3  Dublin    76
     city  temp
1    Oslo     2
5  Vienna     6

Rank numbers

rank() gives each value its place. With ascending=False the biggest value gets 1. Ties need a rule: method="min" gives tied rows the same, best place (like a sports table: 1, 2, 2, 4). Ranks come back as decimals, so convert them with astype("int64").

Pythoneditable
import pandas as pd

df = pd.DataFrame({
    "city": ["Lisbon", "Oslo", "Athens", "Dublin", "Madrid", "Vienna"],
    "country": ["PT", "NO", "GR", "IE", "ES", "AT"],
    "temp": [17, 2, 19, 9, 17, 6],
    "rain": [95, 64, 46, 76, 33, 52],
})

df["warm_rank"] = df["temp"].rank(ascending=False, method="min").astype("int64")
print(df.sort_values("warm_rank")[["city", "temp", "warm_rank"]])
Output
     city  temp  warm_rank
2  Athens    19          1
0  Lisbon    17          2
4  Madrid    17          2
3  Dublin     9          4
5  Vienna     6          5
1    Oslo     2          6
Tip: To sort a single column (a Series), use sort_values() on it too: df["city"].sort_values() gives the names in A to Z order with their labels.

✎ Exercise

Sort the cities by name from A to Z and print the city and country columns with a fresh index. Then print the city with the least rain.

Hint: sort_values("city") then reset_index(drop=True). nsmallest(1, "rain") gives a one-row table; take its city with .iloc[0].

Your codewrite your answer, then Run
import pandas as pd

df = pd.DataFrame({
    "city": ["Lisbon", "Oslo", "Athens", "Dublin", "Madrid", "Vienna"],
    "country": ["PT", "NO", "GR", "IE", "ES", "AT"],
    "temp": [17, 2, 19, 9, 17, 6],
    "rain": [95, 64, 46, 76, 33, 52],
})

# your code here

Expected output:

     city country
0  Athens      GR
1  Dublin      IE
2  Lisbon      PT
3  Madrid      ES
4    Oslo      NO
5  Vienna      AT
Driest: Madrid
Show a solution
Solutioneditable
import pandas as pd

df = pd.DataFrame({
    "city": ["Lisbon", "Oslo", "Athens", "Dublin", "Madrid", "Vienna"],
    "country": ["PT", "NO", "GR", "IE", "ES", "AT"],
    "temp": [17, 2, 19, 9, 17, 6],
    "rain": [95, 64, 46, 76, 33, 52],
})

by_name = df.sort_values("city").reset_index(drop=True)
print(by_name[["city", "country"]])
print("Driest:", df.nsmallest(1, "rain")["city"].iloc[0])
Output
     city country
0  Athens      GR
1  Dublin      IE
2  Lisbon      PT
3  Madrid      ES
4    Oslo      NO
5  Vienna      AT
Driest: Madrid

Check yourself

1. What does df.sort_values("price", ascending=False) do?

2. Two rows tie for first place. What ranks does method="min" give the top three rows?

3. Why use reset_index(drop=True) after sorting?

Spotted a mistake on this page? Tell us