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 or more columns. It covers what happens to missing values (NaN) during a sort, how to move them, and how the same rule affects related tools such as nlargest and rank.
The default: missing values go last
Pandas does not treat a missing value as small or large. It sets missing values aside, sorts the remaining values, and attaches the missing ones at one end. The na_position argument chooses that end. Its default is "last".
Here is the sales table used throughout this tutorial. The row with index 2 has no units value.
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"))
print(df.sort_values("units", ascending=False))The first call returns the rows in index order 1, 5, 3, 0, 4, 2. The second returns 4, 0, 3, 5, 1, 2. The row with the missing value is last in both. Reversing the sort direction does not move it to the top.
Note that units is stored as float64 even though you wrote integers. The None was converted to NaN, and a plain integer column cannot hold NaN, so pandas upgrades the whole column to floats. This is why the values print as 10.0 and 5.0.
Moving missing values to the top
Pass na_position="first" to place them at the beginning:
print(df.sort_values("units", na_position="first"))The row with index 2 now comes first, followed by 1, 5, 3, 0, 4.
Use "first" when missing values are a problem you want to see right away, such as data you need to clean. Use "last" when you want a ranking that is not cluttered by gaps.
Missing values with several sort columns
When you sort by more than one column, the missing-value rule applies to each column within its group. It does not push every row with a gap to the bottom of the whole table.
print(df.sort_values(["region", "units"], na_position="first"))Rows are grouped by region first. Only North has a missing units value, so the missing row comes first inside the North group and not first in the table. The index order is 5, 3, 2, 0, 1, 4: East (7, 8), then North (missing, 10), then South (5, 12).
Compare this with mixed directions and the default placement:
print(df.sort_values(["region", "units"], ascending=[True, False]))The order is 3, 5, 0, 2, 4, 1. In North, the row with 10 comes before the missing row, because the missing row is placed last inside its group.
na_position takes one value, and it applies to every sort column. You cannot ask for missing values first in one column and last in another in a single call. If you need that, sort in stages (see the stability section below) or use a key function.
Controlling the position with a key function
The key argument transforms the values used for ordering, and the original values stay in the result. If your key fills the gaps, the rows are no longer treated as missing during the sort, so na_position has no effect on them.
print(df.sort_values("units", key=lambda s: s.fillna(0)))Here the missing value is treated as 0 for ordering only. It sorts before 5, so the row with index 2 comes first, but the units cell in the output is still NaN. This is useful when a missing value should behave like a specific number, such as zero sales.
The key function receives the whole column as a Series, so it must return a Series of the same length. String methods keep missing values missing: s.str.lower() turns NaN into NaN, and those rows still obey na_position.
names = pd.DataFrame({"name": ["bob", None, "Alice", "carol"]})
print(names.sort_values("name", key=lambda s: s.str.lower()))The result is Alice, bob, carol, and then the missing row last.
Sorting the index
sort_index accepts na_position as well. This matters only when the index itself contains missing labels, which is uncommon but happens after some joins and reshapes.
import numpy as np
s = pd.Series([30, 20, 10], index=[2.0, np.nan, 1.0])
print(s.sort_index())
print(s.sort_index(na_position="first"))The first call orders the labels 1.0, 2.0, NaN. The second orders them NaN, 1.0, 2.0.
Related tools that skip missing values
Several functions near sort_values handle gaps in their own way. Check this before relying on their output.
nlargestandnsmallestnever return rows whose value is missing.df.nlargest(3, "units")returns the rows with 12, 10 and 8. If fewer thannrows have values, you get fewer thannrows.rankleaves missing values asNaNby default (na_option="keep"). Passna_option="bottom"or"top"to give them a rank.
print(df["units"].rank())
print(df["units"].rank(na_option="bottom"))The first call gives 3.0 for 10? No. It ranks 5 as 1, 7 as 2, 8 as 3, 10 as 4 and 12 as 5, and the missing row stays NaN. The second call gives the missing row rank 6.
Removing or filling instead
Sometimes the better choice is to deal with the gap before sorting.
clean = df.dropna(subset=["units"]).sort_values("units")
filled = df.assign(units=df["units"].fillna(0)).sort_values("units")
print(clean)
print(filled)dropna(subset=[...]) removes only rows that are missing in the listed columns. fillna changes the data, so use it only when the replacement value is true to the business meaning. For ordering alone, the key approach above is safer because it leaves the data untouched.
Edge cases and gotchas
- Nullable types. Columns with the
Int64orstringdtype usepd.NA, notNaN.na_positionworks the same way for them. - Several missing rows. Their relative order is not guaranteed with the default algorithm. Pass
kind="stable"to keep them in their original order.kindis applied only when sorting on a single column. A multi-column sort is already stable. - Staged sorts. To get different placement for two columns, sort by the secondary column first, then by the primary one with
kind="stable". The second sort keeps the first sort's order among ties. - Index labels. Sorting moves rows but keeps their labels. Add
ignore_index=Trueif you want fresh labels 0, 1, 2, and so on.
Summary table
| Goal | Tool | Behaviour with missing values |
|---|---|---|
| Sort, gaps at the end | `sort_values("c")` | Last by default |
| Sort, gaps at the start | `sort_values("c", na_position="first")` | First |
| Treat gaps as a number | `key=lambda s: s.fillna(0)` | Values unchanged, order uses 0 |
| Top n rows | `nlargest`, `nsmallest` | Gaps are never returned |
| Ranks | `rank()` | `NaN` kept unless `na_option` is set |
| Ignore gaps entirely | `dropna(subset=[...])` | Rows removed |
Exercise
Using the sales DataFrame, you run df.sortvalues("units", ascending=False, naposition="first"). In what order do the row indexes appear?
Show answer
2, 4, 0, 3, 5, 1. The missing row (index 2) goes first because of na_position="first". The remaining rows are sorted from largest to smallest: 12 (index 4), 10 (index 0), 8 (index 3), 7 (index 5), 5 (index 1).
Exercise
You want the rows sorted by units from smallest to largest, but the row with a missing value should be treated as having 0 units and appear first, without changing the data. Write the call, and explain why na_position is not needed.
Show answer
df.sortvalues("units", key=lambda s: s.fillna(0)). The key function fills the gap with 0 only for ordering, so the row is no longer missing when the sort happens and naposition has nothing to place. The units column in the result still shows NaN.