Sub topic 1
Sorting rows with sort_values
Prerequisites
This chapter assumes you know basic Python syntax and can create a pandas DataFrame and select columns from it. You should also know the difference between a Series (one column) and a DataFrame (a table). The examples use pandas 1.x or 2.x.
The working model
DataFrame.sort_values returns a new DataFrame with its rows reordered by the values in one or more columns. The original DataFrame does not change unless you pass inplace=True. Each row keeps its original index label, so the labels end up out of order after sorting.
The main arguments are:
by: the column name (or list of names) to sort on.ascending:Truefor smallest first (the default),Falsefor largest first.na_position: where missing values go. The default is"last".
The example data
The tutorial uses a small sales table. One units value is missing on purpose, so you can see how sorting treats it.
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))The output is:
region product units price
4 South A 12.0 2.5
0 North A 10.0 2.5
3 East A 8.0 2.5
5 East B 7.0 4.0
1 South B 5.0 4.0
2 North B NaN 4.0Three things to notice:
- The rows run from 12 down to 5, because
ascending=False. - The index column on the left reads 4, 0, 3, 5, 1, 2. Each row carries its original label with it.
unitsis now shown as floats (12.0). A missing value is stored asNaN, a float, so pandas converted the whole column to floats when the DataFrame was built.
The row with the missing value is last. Missing values go to the end by default, even when you sort in descending order.
How the sort works
Internally, pandas works out the order of row positions and then reads the rows in that order. It does not edit the original data. This is why the result must be saved or printed to be useful.
Common errors
- Forgetting to keep the result.
df.sort_values("units")on its own line does nothing lasting. Writedf = df.sort_values("units")or use the result directly. - A misspelled column name. pandas raises
KeyError. Checkdf.columnsfirst. - Passing a list to
ascendingwith one column. The list length must equal the number of columns inby. A mismatch raises aValueError. - Expecting a tidy index. If you want labels renumbered from 0, pass
ignore_index=True. A later chapter covers this.
Sorting a Series
A Series has its own sort_values method. It takes no by argument, because there is only one column of values.
print(df["units"].sort_values(ascending=False))This returns the units values from largest to smallest, still with their original index labels.
Exercise
You run df.sort_values("units", ascending=False) and the row with a missing units value appears at the bottom. Why, and which argument would move it to the top?
Show answer
By default na_position is "last", so missing values go to the end whether the sort is ascending or descending. Passing na_position="first" puts them at the top.
Exercise
What is the difference between df.sort_values("units") and df = df.sort_values("units")?
Show answer
The first returns a sorted copy and discards it, so df is unchanged. The second assigns the sorted copy back to df, so later code sees the sorted order.