Sub topic 7
Listing distinct values with unique
This chapter assumes you can build a Series and a DataFrame, select a column with df["col"], and read basic NumPy-style output. You will learn what Series.unique() returns, how it orders and treats missing values, and which tools to use when unique is not enough.
What unique does
Series.unique() returns the distinct values of a Series. Each value appears once, in the order it first appears in the data. Unlike value_counts, it does not report how often each value occurs.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
cities = df["city"].unique()
print(cities) # Oslo, Rome, Paris, then the missing value
print(len(cities)) # 4Three properties matter in practice:
- Order of first appearance. The result is not sorted.
Oslocomes first because it is in row 0,Romesecond because it is in row 1, and so on. - Missing values are kept. The missing entry in row 6 is a distinct item, so it appears in the result.
- It is hash-based. pandas builds a hash table in one pass over the data, so the cost grows linearly with the number of rows. No sort is involved.
s = pd.Series([3, 1, 3, 2, 1])
print(s.unique()) # [3 1 2], not [1 2 3]What type comes back
For most columns, unique returns a NumPy ndarray, not a Series. That has consequences:
- There is no
.index, and you cannot call Series methods such as.sort_values()on it. - Use
len(...),.tolist(), orsorted(...)to work with it. - To get a Series back, wrap it:
pd.Series(df["city"].unique()).
Some dtypes return a pandas array instead of an ndarray. Categorical columns return a Categorical. Timezone-aware datetime columns return a DatetimeArray. Nullable and string extension dtypes return their own extension array. In every case the contents are the distinct values in order of first appearance.
print(type(df["city"].unique()))
print(type(pd.Series(pd.to_datetime(["2026-01-01", "2026-01-01"])).unique()))The exact class depends on your pandas version and dtype. Do not write code that depends on ndarray specifically. Rely on iteration, len, and .tolist(), which work on all of them.
Missing values
unique has no dropna parameter, unlike value_counts and nunique. It always includes missing values. To exclude them, drop them first:
without_missing = df["city"].dropna().unique()
print(without_missing) # Oslo, Rome, ParisThe kind of missing marker depends on dtype:
| Column dtype | Missing marker in the result |
|---|---|
| float64 | `nan` |
| object holding `None` | `None` stays `None` |
| datetime64 | `NaT` |
| nullable (`Int64`, `string`) | `pd.NA` |
An integer column that has missing values is converted to float64 by default. Its unique result is then floats such as 1.0, plus nan. Use a nullable dtype such as Int64 if you want to keep integers.
For floats, pandas treats all nan values as the same item, so the result contains at most one nan. This differs from plain Python, where float("nan") != float("nan").
Sorting the result
Because the order is the order of first appearance, sort explicitly when you need alphabetical or numeric order.
ordered = sorted(df["city"].dropna().unique())
print(ordered) # ['Oslo', 'Paris', 'Rome']Drop missing values before sorting. In an object column that holds None, sorted compares None with strings and raises a TypeError. NumPy's np.sort has the same problem on object arrays. If you want a sorted Series of distinct values and order matters for display, this is a compact option:
sorted_series = pd.Series(df["city"].dropna().unique()).sort_values(ignore_index=True)Categorical columns
On a categorical column, the distinct values present in the data and the declared categories are different sets. unique reports only the values present.
levels = pd.Categorical(
["b", "a", "b"], categories=["a", "b", "c"]
)
cat = pd.Series(levels)
print(cat.unique()) # values b, a. The categories still list a, b, c
print(cat.cat.categories) # a, b, c: includes the unused "c"
print(cat.cat.categories.size) # 3Use cat.unique() to ask "what occurs in this data?" and cat.cat.categories to ask "what is allowed?". After filtering rows, unused categories remain declared, so the two can drift apart.
Distinct values across several columns
DataFrame has no unique method. Calling df.unique() raises an AttributeError. You have three options, depending on what you mean by "distinct":
- Distinct values of one column. Select it first:
df["city"].unique(). - Distinct rows, or combinations of columns. Use
df.drop_duplicates()ordf[["city", "plan"]].drop_duplicates(). These are covered in a later chapter. - Distinct values pooled from several columns. Flatten the values and use the top-level
pd.unique.
pooled = pd.unique(df[["city", "plan"]].to_numpy().ravel())
print(pooled) # Oslo, free, Rome, pro, Paris, Nonepd.unique is the function form of Series.unique. It accepts a Series, an array, or a list, and it follows the same first-appearance rule. Note that to_numpy() on mixed columns produces an object array, so numbers and strings can end up in one result.
unique, drop_duplicates, and value_counts compared
These three tools are easy to confuse. Each answers a different question.
| Tool | Returns | Keeps original index | Reports counts |
|---|---|---|---|
| `s.unique()` | array of distinct values | No | No |
| `s.drop_duplicates()` | Series with the first row of each value | Yes | No |
| `s.value_counts()` | Series indexed by value, with counts | No | Yes |
drop_duplicates is the right choice when you need to know which rows hold the first occurrence of each value. unique is the right choice when you only need the values themselves, for example to build a filter list or a dropdown.
first_rows = df["city"].drop_duplicates()
print(first_rows.index.tolist()) # [0, 1, 3, 6]A common use of unique is a membership check against a list of allowed values:
allowed = {"Oslo", "Rome", "Paris", "Berlin"}
unexpected = set(df["city"].dropna().unique()) - allowed
print(unexpected) # set(): nothing outside the allowed listChoosing between them
Common errors
AttributeError: 'DataFrame' object has no attribute 'unique'. You calleduniqueon a DataFrame. Select a column, or usedrop_duplicates.- Expecting sorted output.
uniquefollows first appearance. Sort explicitly. TypeErrorwhen sorting. The array containsNoneornanmixed with strings. Drop missing values first.- A
nanorNonein a list you meant to be clean.uniqueincludes missing values. Calldropna()first. - Calling Series methods on the result. The result is usually an array. Wrap it in
pd.Seriesif you need Series behavior.
Exercise
A DataFrame has a float column "score" with values [2.0, 1.0, 2.0, NaN, 3.0, NaN]. Write code that returns the distinct scores as a sorted Python list, with the missing value excluded. What does the code return?
Show answer
sorted(df["score"].dropna().unique()) returns [1.0, 2.0, 3.0]. Without dropna, unique would return [2.0, 1.0, nan, 3.0] in first-appearance order, with a single nan even though NaN appears twice. Sorting a float array that contains nan does not raise an error, but nan is placed last, so dropping it first is the clearer way to exclude it.
Exercise
A column "tier" is categorical with categories ["basic", "plus", "max"], but only "basic" and "max" occur in the data. What do tier.unique() and tier.cat.categories each report?
Show answer
tier.unique() reports only the values present: basic and max, in order of first appearance. tier.cat.categories reports all three declared categories, including the unused "plus".