Sub topic 6
Controlling the order of the result
This chapter assumes you can build a Series or DataFrame, select a column, and call value_counts on it. Here you will learn how pandas orders the output of value_counts. You will also learn how to change that order and how to make the order reproducible.
The default: most frequent first
Series.value_counts() sorts its result by count, from largest to smallest. Two parameters control this:
| Parameter | Default | Effect |
|---|---|---|
| `sort` | `True` | Sort the result by frequency. With `False`, skip sorting. |
| `ascending` | `False` | When sorting, put the smallest counts first if `True`. |
The examples below use a Series of ratings. Some counts tie, so you can see how ties behave.
import pandas as pd
ratings = pd.Series([4, 2, 4, 5, 2, 3, 5, 5, 2, 1])
by_count = ratings.value_counts()
print(by_count)
# Counts are 2 -> 3, 5 -> 3, 4 -> 2, 3 -> 1, 1 -> 1.
# The most frequent values come first.The result is a Series. Its index holds the distinct values from ratings, and its values are the counts. The first row is the mode, the most frequent value. That makes value_counts().index[0] or value_counts().head(1) a quick way to get it.
Ascending order
Set ascending=True to see the rarest values first. This is useful when you hunt for typos or one-off labels in a text column.
import pandas as pd
ratings = pd.Series([4, 2, 4, 5, 2, 3, 5, 5, 2, 1])
rarest_first = ratings.value_counts(ascending=True)
print(rarest_first)
# The values 3 and 1 (count 1) come first, then 4 (count 2),
# then 2 and 5 (count 3).Passing ascending=True reverses the count ordering only. It does not sort the labels.
Skipping the sort with sort=False
With sort=False, pandas does not sort by frequency. The documentation describes this as preserving the order of the data. In pandas 2.x, rows appear in order of first appearance in the Series.
import pandas as pd
ratings = pd.Series([4, 2, 4, 5, 2, 3, 5, 5, 2, 1])
in_data_order = ratings.value_counts(sort=False)
print(in_data_order)
# First appearance order is 4, 2, 5, 3, 1.
# 4 -> 2, 2 -> 3, 5 -> 3, 3 -> 1, 1 -> 1Use sort=False when you want the result to follow the data, for example a log where the first-seen order has meaning. It also skips a sort, which saves a little time on columns with millions of distinct values. In older pandas versions (before 2.0), the order with sort=False was not guaranteed, so check your version before relying on it.
Sorting by the labels with sort_index
Often you want the result ordered by the values themselves, not by how often they occur. Ratings from 1 to 5 read naturally in that order. Call sort_index() on the result, because the distinct values are the index.
import pandas as pd
ratings = pd.Series([4, 2, 4, 5, 2, 3, 5, 5, 2, 1])
by_label = ratings.value_counts().sort_index()
print(by_label)
# 1 -> 1, 2 -> 3, 3 -> 1, 4 -> 2, 5 -> 3
descending_label = ratings.value_counts().sort_index(ascending=False)The chained call counts first and then reorders. Note the difference between the two sort methods on the result:
sort_values()orders by the counts.sort_index()orders by the labels.
Ties and reproducible order
In the first example, the values 2 and 5 both occur three times, and 1 and 3 both occur once. The documentation does not promise an order among tied values. Code that depends on one will break if a pandas version changes. For reports, tests, and exported tables, state the tie-break yourself.
The clearest way is to turn the result into a DataFrame and sort on two columns. The count goes first, then the label. Naming the columns with rename_axis and rename gives the same column names in every pandas version.
import pandas as pd
ratings = pd.Series([4, 2, 4, 5, 2, 3, 5, 5, 2, 1])
table = (
ratings.value_counts()
.rename_axis("rating")
.rename("n")
.reset_index()
.sort_values(["n", "rating"], ascending=[False, True])
.reset_index(drop=True)
)
print(table)
# rating n
# 2 3
# 5 3
# 4 2
# 1 1
# 3 1Here ascending=[False, True] pairs with the sort keys. The counts run from high to low, and ties run from low to high by rating. The final reset_index(drop=True) gives a clean 0 to 4 row index.
An alternative is a stable sort. Sort by label first, then sort by count with kind="stable". Tied counts then keep their label order:
import pandas as pd
ratings = pd.Series([4, 2, 4, 5, 2, 3, 5, 5, 2, 1])
stable = (
ratings.value_counts()
.sort_index()
.sort_values(ascending=False, kind="stable")
)
print(stable)
# 2 -> 3, 5 -> 3, 4 -> 2, 1 -> 1, 3 -> 1Both approaches give the same order here. The DataFrame version is easier to read and adapts when you add more sort keys.
Missing values and order
With dropna=False, the missing value becomes a row like any other. It lands wherever its count puts it. It is not pinned to the end.
import pandas as pd
city = pd.Series(["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None])
print(city.value_counts(dropna=False))
# Oslo -> 3, Rome -> 2, Paris -> 1, NaN -> 1
# The missing value comes last only because its count is lowest.
print(city.value_counts(dropna=False).sort_index())
# Oslo -> 3, Paris -> 1, Rome -> 2, NaN -> 1
# sort_index puts missing labels last by default.If you sort by count with ascending=True, the missing row may appear at the top. A missing value with a high count also appears near the top in the default order. That placement is correct, and it is often what you want to notice. If you do not want it in the output, leave dropna=True, which is the default.
Taking the top or bottom of the result
Since the result is already sorted, head(n) gives the n most frequent values and tail(n) gives the n least frequent. This works because the default order is descending.
import pandas as pd
ratings = pd.Series([4, 2, 4, 5, 2, 3, 5, 5, 2, 1])
top_two = ratings.value_counts().head(2)
print(top_two)
# 2 -> 3 and 5 -> 3 (both tied for the top)The cut falls inside a group of ties when the tied values straddle position n. For example, head(1) returns only one of the two values tied at count 3. If a tie at the boundary matters, use the two-column sort above first. You can also compare against the count at position n and keep every value that matches it.
Common mistakes
- Assuming sort order on a result that was built with
sort=False. The result follows the data, not the counts, sohead()no longer means "most frequent". - Calling
sort_values()when you meantsort_index(). If your labels look scrambled, check which one you used. - Relying on tie order. Two runs on the same data may agree, but a pandas upgrade can change the order. Break ties explicitly whenever the output is saved or compared.
- Forgetting that
ascendingonly affects the count sort. It has no effect whensort=False. - Using the default column names after
reset_index(). They differ between pandas 1.x and 2.x. Rename the axis and the Series yourself, as shown above.
Exercises
Exercise
You run s.value_counts(sort=False) and then call .head(3). Do you get the three most frequent values? Explain.
Show answer
No. With sort=False the result is not ordered by count. In pandas 2.x it follows the order of first appearance in the data, so head(3) returns the first three distinct values seen, whatever their counts. For the three most frequent values, use the default sort and then head(3).
Exercise
Write code that counts the values of a Series s and returns them ordered by count from high to low, with ties ordered by label from low to high. Use the names label and n for the columns.
Show answer
table = s.valuecounts().renameaxis("label").rename("n").resetindex().sortvalues(["n", "label"], ascending=[False, True]).reset_index(drop=True)
Exercise
A column of survey answers has the values "yes", "no", "maybe", and some missing entries. You want a count table in alphabetical order of answer, with the missing entries shown last. Which calls do you use?
Show answer
s.value_counts(dropna=False).sort_index(). The dropna=False argument keeps the missing entries as a row. sort_index() sorts the answers alphabetically and places the missing label last by default.