Sub topic 12
Sorting by values and by index
This chapter assumes you can build a DataFrame, read its Index, and select rows with loc and iloc. Sorting reorders rows, and the result keeps each row's original index label.
Sorting by values
sort_values orders rows by one or more columns. It returns a new DataFrame and leaves the original unchanged.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
by_pop = df.sort_values("pop_m", ascending=False)
print(by_pop)
# Row order: Lima (label 1), Pune (2), Rome (3), Oslo (0)The labels 1, 2, 3, 0 stay attached to their rows. Pandas identifies rows by label, so sorting moves the rows and does not renumber them. Use ignore_index=True if you want a fresh 0, 1, 2, 3 index.
Sorting by several columns
Pass a list of columns. Pass a list to ascending as well to set the direction for each column.
ordered = df.sort_values(["region", "pop_m"], ascending=[True, False])
print(ordered)
# Row order: Pune (AS), Rome (EU, 2.8), Oslo (EU, 0.7), Lima (SA)Pandas sorts by region first. Ties in region are broken by pop_m, largest first.
Sorting by index
sort_index orders rows by their labels instead of their values. It works on Series too.
s = pd.Series([3, 1, 2], index=["c", "a", "b"])
print(s.sort_index())
# a 1
# b 2
# c 3On a DataFrame, df.sort_index() restores the original row order after a value sort. Add axis=1 to sort the column labels.
Missing values
By default, NaN values go last, whatever the sort direction. na_position changes this.
vals = pd.Series([2.0, None, 1.0])
print(vals.sort_values().tolist()) # [1.0, 2.0, nan]
print(vals.sort_values(na_position="first").tolist()) # [nan, 1.0, 2.0]Stability and the diagram
A sort is stable if rows with equal keys keep their original relative order. For a single column, the default algorithm is not guaranteed to be stable. Pass kind="stable" when ties must keep their order. Sorting by several columns always uses a stable method, so this matters mainly for single-column sorts.
Common errors
- Calling
df.sort_values("pop_m")and discarding the result. The original is unchanged, so assign the result:df = df.sort_values("pop_m"). - Passing
inplace=Trueand then also assigning the result. The method returnsNonein that case, so the variable becomesNone. - Sorting a column of strings that look like numbers.
"10"sorts before"9"because the comparison is alphabetical. Convert withastypeorpd.to_numericfirst. - Using
ilocafter sorting and expecting the old positions. Positions change after a sort, but labels do not.
Exercise
Using the df above, write one expression that returns the two most populous cities in the EU region, ordered from largest to smallest, with a fresh 0-based index. What does it return?
Show answer
df[df["region"] == "EU"].sortvalues("popm", ascending=False, ignoreindex=True).head(2). It filters to Rome and Oslo, sorts by popm descending, and renumbers the rows. The result has Rome (2.8) at label 0 and Oslo (0.7) at label 1.