How to Count Unique Values in a Pandas Column

A Denver electronics store sent me its orders CSV and asked how many different customers bought this month. One pandas call counts unique values in the customer column, but my first try with len(unique()) gave the wrong number.

Quick answer: call nunique() on the column. It skips blanks (NaN) unless you pass dropna=False, and value_counts() tells you how often each value appears:

orders["customer"].nunique()              # 5 different customers
orders["customer"].nunique(dropna=False)  # 6, the blank counts too
orders["customer"].value_counts()         # orders per customer

In this tutorial, I’ll count unique values in a pandas column, then per column, per group and with messy data. The outputs come from Python 3.12.5 with pandas 3.0.6.

How Do You Count Unique Values in a Pandas Column with nunique()?

Here’s the store’s file, saved as orders.csv. It has ten orders, and order 1007 has no customer name, which matters in a minute:

order_id,customer,state,product,amount
1001,Emily Carter,TX,Laptop,1249.99
1002,James Miller,CA,Monitor,329.50
1003,Emily Carter,TX,Mouse,24.99
1004,Olivia Brooks,NY,Laptop,1249.99
1005,Noah Bennett,CA,Keyboard,89.00
1006,James Miller,CA,Laptop,1249.99
1007,,FL,Mouse,24.99
1008,Ava Thompson,NY,Monitor,329.50
1009,Olivia Brooks,NY,Mouse,24.99
1010,Emily Carter,TX,Laptop,1249.99

Series.nunique() returns one integer: how many distinct values the column holds.

import pandas as pd

orders = pd.read_csv("orders.csv")

print("States:", orders["state"].nunique())
print("Customers:", orders["customer"].nunique())
print("With blanks:", orders["customer"].nunique(dropna=False))

Output:

States: 4
Customers: 5
With blanks: 6
VS Code output of pandas nunique() counting 4 states, 5 customers and 6 with blanks
nunique() finds 4 states and 5 customers, and 6 once the blank name is counted.

The blank in order 1007 is read as NaN, so the default count is 5 real customers. If you need the names themselves rather than the number, see getting unique values in a pandas DataFrame.

How Many Times Does Each Value Appear? Use value_counts()

nunique() says how many values exist. value_counts() lists each one with its count, sorted from most to least common. Here I put the counts and the shares side by side:

import pandas as pd

orders = pd.read_csv("orders.csv")
products = orders["product"]

counts = products.value_counts()
shares = products.value_counts(normalize=True)
print(pd.DataFrame({"orders": counts, "share": shares}))

Output:

          orders  share
product                
Laptop         4    0.4
Mouse          3    0.3
Monitor        2    0.2
Keyboard       1    0.1
VS Code output of pandas value_counts() counting each product and the share with normalize=True
Laptop leads with 4 of the 10 orders; normalize=True turns the counts into shares.

You get 4 rows, one per product. To find rows that repeat instead, I use the steps in counting duplicates in a pandas DataFrame.

Why Do len(unique()) and nunique() Give Different Counts?

This is the bug from my opening. unique() keeps NaN as one of the values, while nunique() drops it:

import pandas as pd

orders = pd.read_csv("orders.csv")
customers = orders["customer"]

print(customers.unique())
print("len(unique()):", len(customers.unique()))
print("nunique():", customers.nunique())

Output:

<StringArray>
[ 'Emily Carter',  'James Miller', 'Olivia Brooks',  'Noah Bennett',
             nan,  'Ava Thompson']
Length: 6, dtype: str
len(unique()): 6
nunique(): 5

len(unique()) returns 6 and nunique() returns 5. Use whichever matches your question. If you’re unsure what a blank is, see checking if a value is NaN in Python.

Count Unique Values in Every Column of a DataFrame

Call nunique() on the whole DataFrame and you get one count per column. For combinations of columns, drop the duplicate rows and count what’s left:

import pandas as pd

orders = pd.read_csv("orders.csv")

print(orders.nunique())
pairs = orders[["customer", "state"]].drop_duplicates()
print("Customer-state pairs:", len(pairs))

Output:

order_id    10
customer     5
state        4
product      4
amount       4
dtype: int64
Customer-state pairs: 6

order_id has 10 distinct values because it’s a key, and there are 6 customer-state pairs (the blank-name order counts as its own pair here). For plain row totals, see counting rows in a pandas DataFrame.

Count Unique Values per Group with pandas groupby()

Group first, then count: orders.groupby("state")["product"].nunique() gives one number per state. Inside agg() you can count several columns next to other totals, as covered in pandas groupby aggregation functions:

import pandas as pd

orders = pd.read_csv("orders.csv")

summary = orders.groupby("state").agg(
    orders=("order_id", "count"),
    products=("product", "nunique"),
    customers=("customer", "nunique"),
    revenue=("amount", "sum"),
)
print(summary)

Output:

       orders  products  customers  revenue
state                                      
CA          3         3          2  1668.49
FL          1         1          0    24.99
NY          3         3          2  1604.48
TX          3         2          1  2524.97
VS Code output of pandas groupby nunique counting products and customers per US state
Texas has 3 orders but only 2 products and 1 customer; Florida’s single order has no named customer.

Florida shows 0 customers because its only order has a blank name, and nunique() skips NaN inside groups too. My pandas groupby guide explains the split-apply-combine steps.

Common Errors When You Count Unique Values in Pandas

Two problems cause most wrong counts: text that only looks different, and columns that hold lists.

import pandas as pd

raw = pd.Series(["TX", "tx", "TX ", "Texas", "CA", "ca"])
print("Raw states:", raw.nunique())
clean = raw.str.strip().str.upper().replace({"TEXAS": "TX"})
print("Clean states:", clean.nunique())

tags = pd.Series([["sale", "new"], ["new"], ["sale", "new"]])
try:
    tags.nunique()
except TypeError as err:
    print("TypeError:", err)
print("Tag lists:", tags.map(tuple).nunique())
print("Single tags:", tags.explode().nunique())

Output:

Raw states: 6
Clean states: 2
TypeError: unhashable type: 'list'
Tag lists: 2
Single tags: 2
VS Code output of pandas nunique on messy state names before and after cleaning, plus the unhashable list error
Six spellings collapse to 2 states after cleaning; a list column raises TypeError until it’s converted.

Strip spaces and fix the case before you count, or “TX” and “TX ” become two states. Lists can’t be hashed, so turn them into tuples or explode() them first. The same idea works outside pandas; see getting unique values from a list in Python.

Pandas Unique-Count Methods Compared

MethodReturnsCounts NaN?
s.nunique()One integerOnly with dropna=False
s.value_counts()Count per valueOnly with dropna=False
len(s.unique())One integerYes
df.nunique()Count per columnNo
df.groupby(k)[c].nunique()Count per groupNo

Once the counts look right, these pandas guides help with the next step:

Frequently asked questions

How do I count unique values in a pandas column?

Use df["col"].nunique(). It returns the number of distinct values and skips NaN by default.

How do I count unique values including NaN?

Pass dropna=False: df["col"].nunique(dropna=False) counts the blank as one more value.

How do I count how many times each value appears?

Use df["col"].value_counts(). Add normalize=True for shares instead of counts.

How do I count unique values per group?

Use df.groupby("key")["col"].nunique(), or ("col", "nunique") inside agg().

Why does nunique() raise TypeError: unhashable type: ‘list’?

The column holds lists. Convert them with map(tuple) or split them with explode() first.

Where is nunique() documented?

See