skip to content

In pandas 3.0, in what order does DataFrame.value_counts list plan-and-reason combinations with sort=True, and with sort=False?

level: seniorimportance: should knowfreq 38%

answer

  1. one index level per column
  2. ties keep input order
  3. sort=False means appearance order
  4. 2.x sorted by the values
  5. rows with any missing value dropped

basics

~10 s

In pandas 3.0, sort=True orders combinations by count with a stable sort, so ties keep first-appearance order; sort=False keeps the order each combination first appears. In 2.x, sort=False sorted by the column values instead.

solid answer

~40 s

`df.value_counts()` counts each distinct row across the chosen columns and returns a Series with a **MultiIndex**, one level per column, named `count`. With the default `sort=True`, in pandas 3.0, it is a **stable** sort by count, descending, so combinations with equal counts appear in the order they first occur in the frame; the docstring notes the sort was unstable before 3.0. With `sort=False`, in pandas 3.0 the result keeps **input order**, the order of first appearance, matching `Series.value_counts`. In 2.x, `sort=False` sorted the result by the column values, as was documented then. Code that relied on `sort=False` to give a sorted report now needs an explicit `sort_index()`. Rows with a missing value in any counted column are dropped unless `dropna=False`.

code

python · 10 lines
python
import pandas as pd

df = pd.DataFrame({
    "plan":   ["pro", "free", "pro", "free", "pro", "free"],
    "reason": ["support", "price", "price", "price", "support", None],
})

print(df.value_counts(sort=False))
print(df.value_counts(dropna=False))
print(df.value_counts(sort=False).sort_index())   # explicit value order

go deeper

for a junior

Recall that DataFrame.value_counts counts distinct row combinations and returns a Series with one index level per column.

for a middle

Explain the sort=True and sort=False orders in pandas 3.0, including how ties are ordered and how dropna treats partial rows.

for a senior

Diagnose a report or test that reordered after the 3.0 upgrade and fix it by stating the order explicitly with sort_index or sort_values.

for a principal

Treat ordering defaults as a migration risk: ask teams to state sort order explicitly in any output that a human or a test compares.

## What DataFrame.value_counts counts `DataFrame.value_counts(subset=None, normalize=False, sort=True, ascending=False, dropna=True)` counts **distinct rows**: each unique combination of values across the chosen columns. With no `subset`, all columns are used. The result is a **Series**: - its index is a **MultiIndex** with one level per counted column (`plan`, `reason`); - its values are counts, and the Series is named `count`, or `proportion` with `normalize=True`; - passing `subset` as a single label, `subset='reason'`, gives a flat Index, while a list with one label, `subset=['reason']`, still gives a one-level MultiIndex. In the source it is built by grouping on the columns with `sort=False` and taking group sizes, then optionally sorting those sizes. ## Ordering in pandas 3.0 There are two orderings, and **pandas 3.0 changed both**: | Setting | pandas 3.0 order | pandas 2.x order | |---|---|---| | `sort=True` (default) | count descending; ties in first-appearance order (stable sort) | count descending; the sort was unstable, so tie order was not promised | | `sort=True, ascending=True` | count ascending; ties in first-appearance order | count ascending; tie order not promised | | `sort=False` | order in which each combination first appears | sorted by the column values | The `sort=False` change is listed among the breaking API changes in the 3.0 release notes: the old value-sorted order was called "nonintuitive and inconsistent" with `Series.value_counts`, which already kept input order. The stability of `sort=True` is recorded in the method's docstring with "Prior to 3.0.0, the sort was unstable." ## A worked example ```python import pandas as pd df = pd.DataFrame({ "plan": ["pro", "free", "pro", "free", "pro", "free"], "reason": ["support", "price", "price", "price", "support", None], }) df.value_counts() # (pro, support) 2, (free, price) 2, (pro, price) 1 df.value_counts(sort=False) # (pro, support) 2, (free, price) 2, (pro, price) 1 ``` - `(pro, support)` and `(free, price)` tie at 2. In pandas 3.0 the stable sort keeps `(pro, support)` first, because it occurs first, in row 0. - With `sort=False` the order is first appearance: rows 0, 1 and 2 introduce the three combinations in that order. - The last row has a missing reason, so it is dropped by the default `dropna=True`; with `dropna=False` it appears as `(free, NaN)` with a count of 1. On a 2.x install, `sort=False` on the same frame returns `(free, price)`, `(pro, price)`, `(pro, support)`: sorted by plan, then reason. ## What breaks on upgrade 1. **Reports that leaned on `sort=False` for a sorted listing.** A crosstab-like export built with `df.value_counts(sort=False)` used to come out alphabetised. In pandas 3.0 it follows the data. Make the intent explicit with `df.value_counts(sort=False).sort_index()`. 2. **Tests that pinned tie order.** A snapshot test written against 2.x may have recorded whichever tie order the unstable sort produced; in pandas 3.0 ties follow first appearance. Rewrite the expectation, or sort ties explicitly by the index. 3. **Grouped counts.** The release notes apply the same change to `value_counts` called after `groupby`, where the group order and the count order are controlled separately; that variant belongs with grouping. ## Other behaviour to keep in mind - `dropna=True` drops a combination if **any** counted column is missing in that row. - `normalize=True` divides by the total of the kept counts, so dropped rows are outside the denominator. - The result is a Series, not a DataFrame; `.reset_index()` turns it into a table with a `count` column. - The top-level function `pd.value_counts` was removed in pandas 3.0; call the method on a Series instead. ## Writing order-proof code The safest response to a changed default is to stop depending on any default: - when the order of combinations matters, state it: `.sort_index()` for value order, or `.sort_values(ascending=False, kind='stable')` when you re-sort the counts yourself; - when only the numbers matter, compare results as mappings rather than as ordered lists, for example `result.to_dict()` on both sides of a test; - when a report must match a 2.x baseline during a migration, add `sort_index()` to the 3.0 side rather than pinning pandas to 2.x. Each of these reads the same on both versions, so a mixed fleet of notebooks and jobs gives one answer. ## Why it matters in an interview The interesting part is not that the method exists but that its ordering contract changed. A candidate who knows current pandas can explain why a migrated report reordered itself, and fixes the report by stating the order it needs rather than relying on a default.

  • What else changed around value_counts in pandas 3.0?
    The top-level `pd.value_counts` function was removed, so call `pd.Series(values).value_counts()`. The count sort in both the Series and DataFrame methods is documented as stable. And `value_counts` after a `groupby` keeps input order within groups when its own `sort=False` is passed.
  • How do you get the counts back as a regular DataFrame with plan, reason and count columns?
    Call `df.value_counts().reset_index()`. The MultiIndex levels become the `plan` and `reason` columns and the Series values become a column named `count`, or `proportion` when `normalize=True` was passed.

  • DataFrame.value_counts(sort=False) returns the combinations sorted by their values in pandas 3.0
  • Tied counts come out in an arbitrary order in pandas 3.0
  • DataFrame.value_counts returns a DataFrame with a count column
  • Rows with a missing value in one column are counted by default
  • pd.value_counts(series) still works in pandas 3.0

Assumes pandas 3.0: in 2.x DataFrame.value_counts(sort=False) sorted by the column values and its count sort was unstable; 3.0 keeps first-appearance order and sorts counts stably.