Sub topic 10
Counting categories with value_counts
This chapter assumes you can build a DataFrame, select a column as a Series, and read basic pandas output. value_counts answers a common question: how many times does each distinct value appear in a column? It also has several options that change what gets counted, how the result is ordered and how missing values are treated.
What value_counts returns
Series.value_counts() counts each distinct value and returns a new Series. The distinct values become the index, and the counts become the values. The result is sorted from most frequent to least frequent.
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["region"].value_counts())
print(df["region"].value_counts(normalize=True))Every region appears exactly twice in this table. The first call therefore shows a count of 2 for North, South and East. The second call shows 0.333333 for each, because normalize=True divides each count by the total number of counted values.
The output has the layout of a small Series. The index holds the categories, and the values are integers (or floats when normalized).
status = pd.Series(["ok", "ok", "late", "ok", "lost", "late", None, "ok"])
counts = status.value_counts()
print(counts)In pandas 2.x this prints:
ok 4
late 2
lost 1
Name: count, dtype: int64The missing value (None) does not appear. The total of the counts is 7, not 8.
How the result is built
You can think of value_counts as a shortcut for a group-and-count followed by a sort. This diagram shows the steps and where each option applies.
The order of the steps matters for one detail. Normalizing happens after the missing-value filter, so the denominator depends on dropna. The next section shows this.
Options you will use
The main parameters of Series.value_counts are normalize, sort, ascending, dropna and bins.
Proportions and percentages
normalize=True gives fractions that sum to 1. Multiply by 100 for percentages and round for display.
share = status.value_counts(normalize=True)
print((share * 100).round(1))For the status Series, the 7 counted values give ok 57.1, late 28.6 and lost 14.3.
Ordering
The default is descending by count. Set ascending=True to see the rarest values first. To order by the category label instead, chain sort_index() on the result.
print(status.value_counts(ascending=True))
print(status.value_counts().sort_index())The second line returns late 2, lost 1, ok 4, which is alphabetical order. This is useful for ordinal labels such as ratings or sizes, where the natural order of the categories is more meaningful than their frequency. sort_index was covered earlier in this tutorial, and it applies here because the categories are the index.
sort=False skips sorting. The order you get is not something to rely on across pandas versions, so prefer an explicit sort_index() when you need a predictable order.
Missing values
By default dropna=True, so missing values are ignored. Set dropna=False to count them as a category.
print(status.value_counts(dropna=False))
print(status.value_counts(normalize=True, dropna=False))The first call adds a row labelled NaN with a count of 1. The second call changes the denominator from 7 to 8. The value for ok becomes 0.5 instead of about 0.571. Both numbers are correct, but they answer different questions: "what share of valid answers?" versus "what share of all rows?". Pick the one that matches your report, and say which one you used.
Binning numeric data
For a numeric column, bins groups values into intervals before counting. Passing an integer splits the range into that many equal-width intervals.
print(df["units"].value_counts(bins=3))The index of the result is made of intervals, and the missing value in units is excluded. Counting every distinct number in a continuous column, as value_counts() does without bins, usually gives a long list of ones. Use bins when you want a rough distribution. Use pd.cut when you need to control the bin edges and labels.
Counting combinations across columns
DataFrame.value_counts() counts unique rows over the columns you select. The result has a MultiIndex with one level per column.
pairs = df[["region", "product"]].value_counts()
print(pairs)In this table, each of the six region and product pairs occurs once, so every count is 1. To turn the result into an ordinary table with a column of counts, use reset_index and name the count column.
pairs_table = (
df[["region", "product"]]
.value_counts()
.reset_index(name="orders")
)
print(pairs_table)This produces the columns region, product and orders. Rows containing missing values in the selected columns are dropped by default. Pass dropna=False to keep them (this parameter on DataFrame.value_counts was added in pandas 1.3).
value_counts compared with groupby
value_counts is a convenient special case. The following two expressions count rows per region.
by_value_counts = df["region"].value_counts()
by_groupby = df.groupby("region").size().sort_values(ascending=False)
print(by_value_counts)
print(by_groupby)They return the same counts, but they differ in two ways.
groupby(...).size()sorts by group key, not by count, so you have to add the sort yourself.value_countsis limited to counting. If you also need sums or averages for each group, usegroupbywith named aggregation, covered in a later chapter.
Neither one counts the sum of a column. df["region"].value_counts() counts rows, so a region with one order of 1000 units and a region with one order of 1 unit both get a count of 1. For total units, aggregate with groupby("region")["units"].sum().
Common mistakes
- Reading counts as totals. Counts depend on
dropna. If a column has many missing values, the counts add up to less thanlen(df). Comparecounts.sum()withlen(df)to see how many rows were skipped. - Using value_counts on a column that is nearly unique. An identifier column returns one row per value, each with a count of 1. This is a quick way to check for duplicates:
df["id"].value_counts().max() > 1is true when some identifier repeats. - Selecting from the result by position after sorting. The result is sorted by count. Use
.iloc[0]for the most common value and.index[0]for its label, and do not assume the label order matches the original data. - Counting numbers stored as text. The strings
"10"and"10.0"are different categories. Clean and convert types before counting. - Forgetting the column name changes in reset_index. In pandas 2.x,
s.value_counts().reset_index()gives columns named after the original Series andcount. In pandas 1.x it givesindexand the Series name. Passname=or rename the columns explicitly so your code works on both versions.
Quick reference
| Goal | Call |
|---|---|
| Counts, most frequent first | `s.value_counts()` |
| Shares that sum to 1 | `s.value_counts(normalize=True)` |
| Include missing values | `s.value_counts(dropna=False)` |
| Rarest first | `s.value_counts(ascending=True)` |
| Alphabetical by category | `s.value_counts().sort_index()` |
| Counts of numeric ranges | `s.value_counts(bins=4)` |
| Counts of column combinations | `df[["a", "b"]].value_counts()` |
| Result as a table | `s.value_counts().reset_index(name="n")` |
Exercise
Given s = pd.Series(["a", "b", "a", None, "a", "b"]), what does s.value_counts(normalize=True) return, and how does it change with dropna=False?
Show answer
With the default dropna=True, five values are counted: "a" appears 3 times and "b" appears 2 times, so the result is a 0.6 and b 0.4. With dropna=False, the denominator is 6 and the missing value becomes a category, so the result is a 0.5, b about 0.333 and NaN about 0.167.
Exercise
You need a table of region and product pairs with a column named orders, sorted so that the most frequent pair comes first and ties are listed alphabetically by region and then by product. Write the code for the DataFrame df from this chapter.
Show answer
pairs = df[["region", "product"]].valuecounts().resetindex(name="orders") pairs = pairs.sort_values(["orders", "region", "product"], ascending=[False, True, True]) print(pairs)