In pandas, why can len(s.unique()) differ from s.nunique() on the same Series, and what does each one return?
answer
- an array versus a number
- missing values counted or not
- order of first appearance
- dropna default is True
- per column on a frame
basics
~10 sSeries.unique returns an array of the distinct values in order of first appearance, missing value included; Series.nunique returns an int that skips missing values by default. With a NaN present, len(s.unique()) is one higher.
solid answer
~40 s`s.unique()` returns the distinct values as an array, not a Series: a NumPy array for NumPy-backed dtypes, or a pandas extension array for extension dtypes such as categoricals or string columns. It is hash-based, so values come in order of first appearance, unsorted, and a missing value appears once. `s.nunique(dropna=True)` returns a plain `int` and, by default, does not count missing values, so for `['price', 'support', None, 'price']`, `len(s.unique())` is 3 and `s.nunique()` is 2; `s.nunique(dropna=False)` gives 3. On a DataFrame, `df.nunique()` returns a Series with one distinct count per column (or per row with `axis=1`). For distinct rows, rather than values, use `drop_duplicates` or `DataFrame.value_counts`.
go deeper
Recall that unique gives the values as an array and nunique gives a count, and that only unique includes a missing value by default.
Explain that unique is hash-based and unsorted, that nunique has a dropna switch, and how DataFrame.nunique works per column.
Show that cardinality checks and generated filter lists account for missing values and do not depend on the order unique returns.
Encourage data-quality rules that report missing and distinct counts separately, so a uniqueness check never hides a completeness problem.
## Two questions about distinct values pandas answers "which values occur?" and "how many distinct values are there?" with two different methods on a **Series** (a single labelled column): - `Series.unique()` answers **which**: it returns the distinct values themselves. - `Series.nunique(dropna=True)` answers **how many**: it returns a single integer. They disagree on one point, missing values, and that is why the obvious check `len(s.unique()) == s.nunique()` can fail. ## What unique returns - **An array, not a Series.** For NumPy-backed dtypes such as `int64` or `float64` it is a NumPy array. For extension dtypes (categoricals, nullable integers like `Int64`, time-zone-aware datetimes, string columns) it is a pandas extension array of the same dtype, so a categorical keeps its categories. - **In order of first appearance.** The method is hash-based and does not sort; the docstring says so explicitly. `np.unique`, from NumPy, sorts; `Series.unique` does not. - **Missing values included.** A missing value appears once in the result, wherever it first occurs. - **No index.** The original row labels are gone. If you need a Series with labels, `s.drop_duplicates()` keeps the first row of each value with its label. `Index.unique()` is the index's counterpart and returns an **Index**, not an array. ## What nunique returns - **A plain integer** for a Series. - **Missing values excluded by default.** `dropna=True` removes them from the count, as the user guide puts it: "the number of unique non-NA values". - `nunique(dropna=False)` counts a missing value as one more distinct value. - On a **DataFrame**, `df.nunique()` returns a Series with one count per column; `df.nunique(axis=1)` counts per row instead. ## Side by side | Call | Returns | Missing value | Order | |---|---|---|---| | `s.unique()` | array of values | included once | first appearance | | `s.nunique()` | `int` | excluded | not applicable | | `s.nunique(dropna=False)` | `int` | counted once | not applicable | | `s.drop_duplicates()` | Series, labels kept | kept once | first appearance | | `s.value_counts()` | Series of counts | excluded | by count, descending | | `df.nunique()` | Series, one per column | excluded | column order | Because `value_counts` also excludes missing values by default, `s.value_counts().size == s.nunique()` holds. ## A worked example ```python import pandas as pd reason = pd.Series(["price", "support", None, "price"]) len(reason.unique()) # 3: price, support and the missing value reason.nunique() # 2: missing value not counted reason.nunique(dropna=False) # 3 ``` ## Where this bites 1. **Cardinality checks.** A data-quality rule like "every contact has a distinct email" compares `crm['email'].nunique()` with `len(crm)`. Missing emails lower `nunique` and the rule fails for the wrong reason; check `isna().sum()` separately. 2. **Building lookup lists.** Code that loops over `s.unique()` to build dropdown options or query filters gets a missing value as one of the options, which then matches nothing. 3. **Comparing with expectations.** Tests that compare `s.unique()` to a sorted list fail intermittently as row order changes; sort the result first, for example with `sorted(...)` or `pd.Series(s.unique()).sort_values()`. 4. **Distinct rows.** Neither method counts distinct combinations across columns. Use `len(df.drop_duplicates(subset=[...]))` or `df.value_counts(subset=[...]).size`, and remember the latter drops rows with a missing value. ## Choosing the right call 1. Need the **values** to loop over or display? `s.unique()`, then drop or handle the missing value explicitly. 2. Need the **number** of distinct real values? `s.nunique()`. 3. Need to know whether missing counts as a category? `s.nunique(dropna=False)`, and say so in the report. 4. Need the values **with how often** each occurs? `s.value_counts()`, adding `dropna=False` to see the missing count. 5. Need the distinct values **as a Series with labels**? `s.drop_duplicates()`. Picking the call that matches the question avoids the conversions, such as wrapping an array back into a Series, that clutter cleaning code. ## Counting per group `nunique` also exists on grouped data, for example distinct reasons per plan, but that is grouping work and is covered with grouping and aggregation. Here the question is about one Series or one frame at a time.
- How do you get the distinct values sorted, as a Series?`pd.Series(s.unique()).sort_values()` works, or `s.drop_duplicates().sort_values()` if you also want to keep the label of each value's first row. `unique` itself never sorts, because it is hash-based and returns values in order of first appearance.
- How do you count distinct combinations of two columns?`nunique` works one column at a time. For combinations, use `len(df.drop_duplicates(subset=['plan', 'reason']))`, which treats missing values as equal, or `df.value_counts(subset=['plan', 'reason']).size`, which by default drops rows with a missing value.
- Series.unique returns the distinct values sorted in ascending order
- Series.unique returns a Series that keeps the original row labels
- nunique counts a missing value as a distinct value by default
- unique leaves out missing values, just like nunique
- df.nunique() returns a single count of distinct rows