Sub topic 4
Counting occurrences with value_counts
This chapter assumes you know basic Python syntax, can create a pandas Series and DataFrame, and can select a column from a DataFrame with df["name"]. It covers the call you will use most often when exploring a column: Series.value_counts().
What value_counts does
value_counts answers the question "how many times does each distinct value appear?" It takes a Series and returns a new Series with these properties:
- The index holds the distinct values from the original column.
- The values hold how many times each one occurred.
- Rows are sorted from most frequent to least frequent.
- Missing values are left out by default.
The examples in this chapter use one small DataFrame. Its city column has one missing value.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
counts = df["city"].value_counts()
print(counts)The output is:
city
Oslo 3
Rome 2
Paris 1
Name: count, dtype: int64The data has seven rows, but the counts add up to six. The missing value was dropped, which the next sections explain.
Reading the result
The result is an ordinary Series, so everything you know about Series applies. You can look up a value by label, slice the top entries, or loop over it.
print(counts["Oslo"]) # 3
print(counts.get("Berlin", 0)) # 0, a label that never occurred
print(counts.head(2)) # the two most frequent values
print(counts.index.tolist()) # ['Oslo', 'Rome', 'Paris']
print(counts.sum()) # 6Use .get(label, 0) when the value might not exist. Plain indexing with counts["Berlin"] raises a KeyError.
Naming differences between versions
The names on the result changed in pandas 2.0:
| pandas version | Series name | Index name |
|---|---|---|
| 1.x | the column name (`city`) | none |
| 2.0 and later | `count` | the column name (`city`) |
This matters when you turn the result into a DataFrame. The following code produces the same columns in both versions:
table = counts.rename_axis("city").reset_index(name="n")
print(table) city n
0 Oslo 3
1 Rome 2
2 Paris 1Calling rename_axis("city") sets the index name explicitly. Calling reset_index(name="n") names the counts column explicitly. Neither step depends on the version's defaults.
Missing values
By default value_counts uses dropna=True, so None and NaN do not appear in the result. The sum of the counts is therefore the number of non-missing entries, not the number of rows.
print(df["city"].value_counts(dropna=False))city
Oslo 3
Rome 2
Paris 1
NaN 1
Name: count, dtype: int64The None in the object column is reported as NaN, with a count of 1. Now the counts add up to seven, the length of the column.
You can check how many values were left out without a second call:
n_missing = len(df["city"]) - df["city"].value_counts().sum()
print(n_missing) # 1df["city"].isna().sum() gives the same number and is easier to read.
Counting any dtype
value_counts works on any column type: strings, integers, booleans, dates, and categoricals. Equality decides what counts as "the same value".
print(df["plan"].value_counts())plan
pro 4
free 3
Name: count, dtype: int64Floats follow normal equality. Values such as 0.1 + 0.2 and 0.3 are different floats, so they are counted as separate entries. Round them first if you want them grouped.
Strings are case-sensitive and whitespace-sensitive. "Oslo", "oslo", and "Oslo " are three different values. If a count looks split, clean the text first:
messy = pd.Series(["Oslo", "oslo", "Oslo ", "Rome"])
clean = messy.str.strip().str.lower()
print(clean.value_counts())oslo 3
rome 1
Name: count, dtype: int64The value_counts result always has a data-type dependent index, but the counts are always integers (int64), unless you use normalize=True.
The main parameters
The full signature is Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True). This chapter focuses on the default behavior and on dropna. The other parameters are listed here so you know what exists. Later chapters cover them in detail.
| Parameter | Default | Effect |
|---|---|---|
| `normalize` | `False` | Return fractions that sum to 1 instead of counts |
| `sort` | `True` | Sort by count; `False` leaves the order unspecified |
| `ascending` | `False` | `True` puts the least frequent value first |
| `bins` | `None` | For numeric data, count values inside intervals |
| `dropna` | `True` | Exclude missing values from the result |
A quick example of the two most common options:
print(df["city"].value_counts(normalize=True))
print(df["city"].value_counts(ascending=True))The first call returns Oslo 0.500000, Rome 0.333333, and Paris 0.166667. These are fractions of the six non-missing values. The second call lists Paris first.
Ties and ordering
Sorting is by count only. When two values have the same count, their relative order is not something you should rely on. This is a common source of tests that pass on one machine and fail on another.
tied = pd.Series(["a", "b", "b", "c", "c"])
print(tied.value_counts().sort_index())Chaining sort_index() after value_counts() sorts by label. That gives a reproducible order, with b and c listed in alphabetical order and not in whatever order the tie produced. If you want "by count, then by label" in a single result, sort the counts as a DataFrame:
by_both = (
tied.value_counts()
.rename_axis("item")
.reset_index(name="n")
.sort_values(["n", "item"], ascending=[False, True])
)
print(by_both)Common errors
- Calling it on a DataFrame and expecting per-column output.
df.value_counts()counts unique rows, which is a different operation covered later in this tutorial. For one column, select it first withdf["city"].value_counts(). - Treating the result as a column. The values you counted are in the index, not in a column. Use
reset_index()before merging or plotting with a library that expects columns. - Forgetting that missing values are dropped. Percentages that do not add up usually come from this.
- Assuming
df["city"].value_counts()["Berlin"]returns 0. It raisesKeyError. Use.get. - Writing code that depends on the Series name. The default name changed in pandas 2.0, so set names explicitly.
Summary of behavior
value_countsreturns a Series with the distinct values as the index and their counts as data.- The default order is most frequent first, and ties have no guaranteed order.
- Missing values are excluded unless you pass
dropna=False. - It works on any dtype, and equality decides what is "the same".
- The result is a Series, so label lookup, slicing, and
reset_indexall apply.
Exercise
A column status contains ["ok", "ok", "fail", None, "ok", "fail", None, "Ok"]. Without running code, what does status.value_counts() return, and what does adding dropna=False change?
Show answer
With the default, the result is ok 3, fail 2, Ok 1. "Ok" is a separate value because matching is case-sensitive, and the two None entries are dropped, so the counts sum to 6 of the 8 rows. With dropna=False, a NaN entry with count 2 is added, so the counts sum to 8. To merge "ok" and "Ok" you would first normalize case, for example with status.str.lower().
Exercise
You run counts = df["city"].value_counts() and want a two-column DataFrame with columns city and n that works on both pandas 1.x and 2.x. Which call do you use?
Show answer
counts.renameaxis("city").resetindex(name="n"). renameaxis sets the index name explicitly and resetindex(name="n") names the counts column, so the result does not depend on the version's default names.