Sub topic 1
Sorting Rows with `sort_values`
Prerequisites
You should know basic Python syntax, how to create a pandas DataFrame, and the difference between a Series and a DataFrame.
Assume df contains sales records with region, product, units, and price columns. sort_values returns rows ordered by one or more column values. It does not change df unless you assign the result or use inplace=True.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})
print(df.sort_values("units", ascending=False))ascending=False puts the largest values first. The default is True, which puts the smallest values first.
Sorting by several columns, ascending and descending
Pass a list of columns to define tie-breakers. Pass one Boolean value per column in ascending.
print(df.sort_values(
["region", "units"],
ascending=[True, False],
))This sorts regions alphabetically. Within each region, it sorts units from largest to smallest. The first column is the primary sort key.
Where missing values go when you sort
pandas places missing values last by default, regardless of sort direction. Use na_position="first" to place them first.
print(df.sort_values("units", ascending=False, na_position="first"))The missing units value therefore appears before the numeric values. Choose this option explicitly when missingness has meaning in your report.
Sorting by index labels
Use sort_index when the order of index labels matters rather than the values in a column.
print(df.sort_index(ascending=False))This reverses the default integer index. For a meaningful custom index, the same method orders those labels.
Sorting with a key function
The key argument transforms values for comparison without changing the stored values. For example, sort text without treating uppercase and lowercase as different.
print(df.sort_values(
"region",
key=lambda values: values.str.lower(),
ignore_index=True,
))ignore_index=True creates a new consecutive index after sorting. Without it, the original row labels move with their rows.
Exercise
How would you sort df by price from highest to lowest, putting missing prices first?
Show answer
Use df.sort_values("price", ascending=False, na_position="first").