Column cardinality checks
Profile categorical or identifier columns by measuring how many different values each contains.
Pandas · Module
DataFrame.nunique counts distinct values along an axis and returns a Series. It excludes NaN by default, and can count per row with axis=1 or include missing values with dropna=False.
DataFrame.nunique counts distinct values along a chosen axis and returns the counts as a Series. By default it excludes missing values; set dropna=False to include them, and use axis=1 or "columns" to count across each row.
DataFrame.nunique(axis=0, dropna=True)| Name | Type | Description |
|---|---|---|
axis | {0 or 'index', 1 or 'columns'}, default 0 | Axis to use: 0 or "index" counts down each column; 1 or "columns" counts across each row. Defaults to 0. |
dropna | bool, default True | Whether to include NaN values in the distinct counts. Defaults to True, meaning they are excluded. |
Series with counts of unique values per row or column, depending on axis.
import pandas as pd
scores = pd.DataFrame({
"math": [90, 90, 80],
"english": [85, 85, None],
})
by_column = scores.nunique()
by_row_including_missing = scores.nunique(axis="columns", dropna=False)
print(by_column)
print(by_row_including_missing)Counts distinct values for each column and then for each row, treating the missing value as a distinct value in the second calculation.
Profile categorical or identifier columns by measuring how many different values each contains.
Detect rows containing varied values by counting distinct entries across each row.
Include missingness as part of a row or column's distinct-value profile when that distinction matters.
DataFrame.nunique returns a Series containing the number of distinct values for each column by default. Its default axis is 0, and missing values are omitted unless dropna is set to False.
Follow-up: How would you count distinct values across rows? Use axis=1 or the equivalent axis="columns".
Use axis=1, or axis="columns", to count unique values within each row. The result is a Series indexed by the DataFrame's row labels.
Follow-up: How can missing values affect that result? They are ignored by default; pass dropna=False to include them.
The method accepts axis values 0 or "index" and 1 or "columns". The dropna boolean controls whether NaN values participate in the count and defaults to True.
Follow-up: What type is returned for either direction? A Series containing counts per column or per row, depending on the selected axis.
Series.nuniqueDataFrame.count