Sub topic 6
Controlling the order of the result
This chapter assumes you can call value_counts on a column and read its output. It covers the ordering rules of that result and how to change them.
The default order
Series.value_counts() sorts by count, largest first. The index holds the distinct values and the data holds the counts, so the ordering depends on the counts. Reading the top of the result gives you the most common values.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
print(df["city"].value_counts())
# Oslo 3
# Rome 2
# Paris 1Because the result is already sorted, .head(n) gives the n most frequent values.
top_two = df["city"].value_counts().head(2) # Oslo 3, Rome 2Reversing and disabling the sort
Two parameters control the sort:
ascending=Trueputs the least frequent values first.sort=Falseskips sorting by count.
rarest_first = df["city"].value_counts(ascending=True) # Paris 1, Rome 2, Oslo 3
unsorted = df["city"].value_counts(sort=False) # no count orderingWith sort=False, recent pandas versions usually list values in order of first appearance. The documentation does not promise this, so don't build code on it. If you need a specific order, sort explicitly.
Sorting by the labels
To list values alphabetically or numerically, sort the result by its index with sort_index().
by_label = df["city"].value_counts().sort_index()
# Oslo 3, Paris 1, Rome 2
by_label_desc = df["city"].value_counts().sort_index(ascending=False)
# Rome 2, Paris 1, Oslo 3This is the usual choice when the labels have a natural order, such as ratings from 1 to 5. A count-sorted result would scramble that order.
Ties
When two values have the same count, the default result does not guarantee which one comes first. Reports and tests that depend on the order can then change between runs or versions. To make the order deterministic, sort by label first, then do a stable sort by count.
s = pd.Series(["b", "a", "c", "a", "b", "d"])
counts = (
s.value_counts()
.sort_index()
.sort_values(ascending=False, kind="stable")
)
print(counts)
# a 2
# b 2
# c 1
# d 1A stable sort keeps tied items in their existing order, which here is alphabetical. The result is the same every time.
Common mistakes
- Calling
sort_values()on the result withoutascending=Falsereverses the intended order, becausesort_valuesdefaults to ascending. - Passing
sort=Falseand expecting the labels to be sorted. It only skips the count sort. - Reading
[0]on the result to get the top value. The index holds the labels, so use.iloc[0]for the top count or.index[0]for the top label.
Exercise
Using the city column above, write one expression that lists each city with its count, sorted by count from highest to lowest, with ties broken alphabetically by city name.
Show answer
df["city"].valuecounts().sortindex().sort_values(ascending=False, kind="stable"). Sorting by label first sets the tie order, and the stable sort by count keeps it. The result is Oslo 3, Rome 2, Paris 1.