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 sort_values output from the earlier chapters.
What value_counts does
Series.value_counts() counts how often each distinct value appears in a column. It returns a new Series. The index holds the distinct values and the data holds the counts, sorted from most to least frequent. That is a count and a sort in one call, so it is the quickest way to inspect a categorical column.
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))Each region appears twice in this data. The first call returns a count of 2 for every region. The second call, with normalize=True, returns proportions that add up to 1. Each region gets about 0.333.
When counts tie, don't rely on the order of the tied labels. If the order matters, sort the result explicitly with sort_index().
A tie-free example
A Series with distinct counts makes the ordering visible.
s = pd.Series(["a", "b", "a", "c", "a", "b"])
print(s.value_counts())a 3
b 2
c 1
Name: count, dtype: int64In pandas 2.x the result Series is named count. For a column such as df["region"], the index is named region. Older versions named the result after the column and left the index unnamed. Check your version if your output differs.
Useful arguments
| Argument | Effect | Default |
|---|---|---|
| `normalize` | Return proportions instead of counts | `False` |
| `sort` | Sort by frequency | `True` |
| `ascending` | Sort from least to most frequent | `False` |
| `dropna` | Leave out missing values | `True` |
Missing values
By default value_counts leaves out NaN. The counts then add up to fewer than the number of rows, and this can mislead you. Pass dropna=False to count missing values as their own category.
print(df["units"].value_counts(dropna=False))This prints one row per distinct value, plus a NaN row with a count of 1. Without dropna=False, NaN would not appear.
Common errors
- Calling it on a DataFrame column list.
df[["region"]].value_counts()works in recent pandas, but it returns a Series with a MultiIndex of the selected columns. For a plain count, usedf["region"]. - Counting numeric columns.
df["units"].value_counts()counts exact values. It does not bin them. For ranges, usepd.cutfirst or passbins=to the Series method. - Expecting a DataFrame. The result is a Series. To get a table with ordinary columns, call
reset_index().
counts = df["region"].value_counts().reset_index()
print(counts)This gives a DataFrame with columns region and count, which you can merge or plot like any other table.
value_counts versus groupby
df["region"].value_counts() gives the same counts as df.groupby("region").size(). The difference is the order. value_counts sorts by frequency, while groupby sorts by group label. Use groupby when you also need other statistics per group. Use value_counts for a fast look at one column.
Exercise
A column status has 8 rows: 5 "ok", 2 "fail" and 1 missing value. What does df["status"].value_counts(normalize=True) return for "ok", and how do you make the missing value appear as a category?
Show answer
It returns 5/7, about 0.714, because the missing value is dropped from the denominator. Pass dropna=False to include it. "ok" then becomes 5/8 = 0.625 and the missing value gets 0.125.