TExcelTAD
Home › pandas › Counting and Unique Values

Counting and Unique Values

"How many of each?" is one of the most common questions you ask a dataset. How many orders per country? Which browser do most visitors use? pandas answers it with value_counts(), unique() and nunique().

unique() and nunique()

python · try it yourself
import pandas as pd

tickets = pd.DataFrame({
    "id": range(1, 11),
    "priority": ["low", "high", "medium", "low", "low", "high", "medium", "low", "urgent", "medium"],
    "channel": ["email", "phone", "email", "chat", "email", "email", "chat", "phone", "phone", "email"],
})
print(tickets["priority"].unique())
print(tickets["priority"].nunique())
print(tickets.nunique())
['low' 'high' 'medium' 'urgent']
4
id          10
priority     4
channel      3
dtype: int64

unique() returns the distinct values in order of first appearance; nunique() just counts them. On a whole DataFrame, nunique() reports each column.

value_counts()

value_counts() counts each distinct value, most frequent first:

python · try it yourself
import pandas as pd

tickets = pd.DataFrame({
    "priority": ["low", "high", "medium", "low", "low", "high", "medium", "low", "urgent", "medium"],
    "channel": ["email", "phone", "email", "chat", "email", "email", "chat", "phone", "phone", "email"],
})
print(tickets["channel"].value_counts())
print(tickets["channel"].value_counts(normalize=True))
channel
email    5
phone    3
chat     2
Name: count, dtype: int64
channel
email    0.5
phone    0.3
chat     0.2
Name: proportion, dtype: float64

normalize=True turns counts into fractions that add up to 1, handy for "what share of tickets came by email?".

Options worth knowing

python · try it yourself
import numpy as np
import pandas as pd

answers = pd.Series(["yes", "no", np.nan, "yes", "yes", np.nan, "no", "maybe"])
print(answers.value_counts())
print(answers.value_counts(dropna=False))
print(answers.value_counts(ascending=True).index.to_list())
print(answers.value_counts().sort_index())
yes      3
no       2
maybe    1
Name: count, dtype: int64
yes      3
no       2
NaN      2
maybe    1
Name: count, dtype: int64
['maybe', 'no', 'yes']
maybe    1
no       2
yes      3
Name: count, dtype: int64
Argument Effect
normalize=True fractions instead of counts
dropna=False also count missing values
ascending=True least frequent first
bins=4 for numbers: count values in 4 equal-width ranges

By default missing values are not counted, which can hide data problems. dropna=False shows them.

Counting combinations

On a DataFrame, value_counts() counts each unique combination of the selected columns:

python · try it yourself
import pandas as pd

tickets = pd.DataFrame({
    "priority": ["low", "high", "medium", "low", "low", "high", "medium", "low", "urgent", "medium"],
    "channel": ["email", "phone", "email", "chat", "email", "email", "chat", "phone", "phone", "email"],
})
print(tickets[["channel", "priority"]].value_counts().head(4))
channel  priority
email    low         2
         medium      2
chat     low         1
         medium      1
Name: count, dtype: int64

For a full grid of counts (every channel × every priority) use pd.crosstab(), covered in the Pivot Tables lesson.

Counting numbers in ranges

python · try it yourself
import pandas as pd

ages = pd.Series([23, 35, 41, 29, 52, 38, 61, 27, 33, 45])
print(ages.value_counts(bins=[20, 30, 40, 50, 70]).sort_index())
(19.999, 30.0]    3
(30.0, 40.0]      3
(40.0, 50.0]      2
(50.0, 70.0]      2
Name: count, dtype: int64

The labels like (30.0, 40.0] mean "greater than 30, up to and including 40". The Binning lesson goes deeper with pd.cut().

Filtering by frequency

A common pattern is to keep only frequent categories, for example to group rare ones as "other":

python · try it yourself
import pandas as pd

browser = pd.Series(["Chrome", "Firefox", "Chrome", "Safari", "Edge", "Chrome",
                     "Safari", "Opera", "Chrome", "Firefox"])
counts = browser.value_counts()
common = counts[counts >= 2].index
grouped = browser.where(browser.isin(common), "other")
print(grouped.value_counts())
Chrome     4
Firefox    2
Safari     2
other      2
Name: count, dtype: int64

where(condition, other) keeps values where the condition is true and replaces the rest with "other".

Test yourself

What does s.nunique() return?

  1. The distinct values
  2. The number of distinct values
  3. The most frequent value
  4. The number of missing values

How do you get the share of each category instead of the count?

  1. value_counts(percent=True)
  2. value_counts(normalize=True)
  3. value_counts() / 100
  4. value_counts(share=True)

Does value_counts() count missing values by default?

  1. Yes
  2. No, you need dropna=False
  3. Only for numbers
  4. Only for text