Sub topic 3
Where missing values go when you sort
This chapter assumes you can build a DataFrame, select columns, and call sort_values on one column. Real data often has gaps, so you need to know what happens to those rows when you sort.
The default: missing values go last
pandas stores a missing number as NaN (not a number). NaN is not larger or smaller than any other value, so pandas cannot place it by comparison. It uses a fixed rule instead. By default, sort_values puts missing values at the end.
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))Row 2 has no units value, so it appears last. The other rows run from 12 down to 5.
The rule does not depend on direction. The ascending sort df.sort_values("units") also puts row 2 last. Missing values are not treated as the smallest or the largest value.
print(df.sort_values("units")["units"].tolist())
print(df.sort_values("units", ascending=False)["units"].tolist())[5.0, 7.0, 8.0, 10.0, 12.0, nan]
[12.0, 10.0, 8.0, 7.0, 5.0, nan]Moving them with na_position
The na_position argument takes "last" (the default) or "first". Use "first" when you want gaps to be the first thing a reader sees, for example during data cleaning.
print(df.sort_values("units", na_position="first"))Row 2 now comes first, followed by the values 5 to 12 in ascending order.
Several columns
With a list of columns, na_position applies to every column in the sort. You cannot give each column its own setting.
print(df.sort_values(["units", "region"], na_position="first"))Removing missing rows instead
Sometimes you do not want those rows at all. Drop them before sorting, and name the column in subset so that gaps in other columns do not remove rows.
clean = df.dropna(subset=["units"]).sort_values("units", ascending=False)
print(clean)| Goal | Call |
|---|---|
| Gaps at the bottom (default) | `sort_values("units")` |
| Gaps at the top | `sort_values("units", na_position="first")` |
| No rows with gaps | `dropna(subset=["units"])` then sort |
Exercise
Using the DataFrame above, you sort by units in descending order and set na_position="first". Which row index appears first, and which row index appears last?
Show answer
Row 2 appears first, because it is the only row with a missing units value and na_position="first" puts it at the top. Row 1 appears last, because it has the smallest real value (5) and the values run from 12 down to 5 after the missing row.