Sub topic 7
Listing Distinct Values with unique
This chapter assumes you can build a pandas Series and DataFrame, select a column, and read basic Python. It covers Series.unique, what it returns, and how it treats missing values.
What unique returns
unique returns the distinct values of a Series in the order they first appear. It does not sort them, and it keeps one copy of each value.
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)The output is:
['Oslo' 'Rome' 'Paris' None]Two details matter here:
- The result is a NumPy array, not a Series. It has no index and no counts.
- The missing value appears in the result as its own item.
uniquedoes not drop it.
Missing values are kept
Many pandas counting methods skip missing values by default. unique does not. If a column contains None or NaN, one missing entry appears in the output. All missing entries in the column collapse into that one item.
This is the main source of surprises. If you loop over unique() and assume every item is a real city, the missing value will reach your code. Remove it before you use the list:
real_cities = df["city"].dropna().unique()
print(real_cities)The output is:
['Oslo' 'Rome' 'Paris']Calling dropna first keeps the missing value out of the result. This also means the length of unique() can differ from nunique(), which you will meet in the next chapter.
Order of first appearance
Because unique follows the order in which values first appear, the result depends on the row order of your data. If you need a stable, readable list, sort it yourself. Sorting a list that contains a missing value can fail or place it unpredictably, so drop missing values first.
sorted_cities = sorted(df["city"].dropna().unique())
print(sorted_cities)The output is:
['Oslo', 'Paris', 'Rome']unique works on a Series only
unique is a Series method. A DataFrame has no unique method, so df.unique() raises an AttributeError. Select a column first, as in df["plan"].unique().
To see the distinct rows across several columns, use drop_duplicates, which a later chapter covers.
flowchart TD
A[Series column] --> B[unique]
B --> C[Array of distinct values]
C --> D{Missing value in column?}
D -->|Yes| E[One missing item in the array]
D -->|No| F[Only real values]Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling `df.unique()` on a DataFrame | `AttributeError` | Select a column first |
| Assuming the result is sorted | Order follows the data | Use `sorted(...)` |
| Forgetting the missing value | `None` or `NaN` reaches later code | Use `dropna()` first |
| Expecting counts | `unique` returns values only | Use `value_counts` |
Exercise
A column status holds ["open", "closed", "open", NaN, "closed"]. What does df["status"].unique() return, and how would you get only the real values in sorted order?
Show answer
It returns ['open', 'closed', nan] as an array, in order of first appearance, with the missing value included. To get only real values in sorted order, use sorted(df["status"].dropna().unique()), which gives ['closed', 'open'].
Exercise
Why does df.unique() fail, and what should you write instead to list the distinct values of the plan column?
Show answer
unique is a Series method and a DataFrame does not have it, so pandas raises an AttributeError. Write df["plan"].unique().