pandas unique values multiple columns
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Finding unique values across multiple columns in pandas requires different approaches depending on whether you want unique combinations of column values (unique rows) or a flat set of all distinct values appearing in any of the columns. For unique row combinations, use drop_duplicates() or groupby. For a flat set of all values, use np.unique() or pd.unique() on the stacked columns. Understanding the distinction is key to choosing the right method.
Sample Data
Unique Combinations of Multiple Columns
drop_duplicates()
groupby for Unique Combinations with Counts
value_counts on Multiple Columns
Flat Set of All Unique Values Across Columns
When you want all distinct values from multiple columns combined into one set.
Unique Values Per Column
Filtering by Unique Combinations
Unique Combinations with Aggregation
Common Pitfalls
- Confusing
unique()withdrop_duplicates():df['col'].unique()returns unique values from a single Series.df[['col1', 'col2']].drop_duplicates()returns unique row combinations. Calling.unique()on a multi-column DataFrame selection raisesTypeError. - Using
.values.ravel()on mixed types: When columns have different dtypes (e.g., string and int),.values.ravel()converts everything to object dtype. This may cause unexpected behavior in comparisons. Ensure columns are compatible types before combining. - Forgetting
reset_index(drop=True):drop_duplicates()preserves original index values, creating gaps (e.g., 0, 1, 3). If downstream code assumes consecutive indices, call.reset_index(drop=True)after deduplication. nunique()counting NaN as a unique value: By default,nunique()excludes NaN. If your data contains NaN and you need it counted, usedf['col'].nunique(dropna=False). This difference betweennunique()andlen(unique())can cause confusion.- Performance with large DataFrames:
drop_duplicates()on many columns creates a hash of each row, which is slow for millions of rows with many columns. For performance, consider sorting first or usinggroupby().first()which can be faster on sorted data.
Summary
- Use
df[cols].drop_duplicates()for unique combinations of rows across multiple columns - Use
pd.unique(df[cols].values.ravel())for a flat array of all distinct values across columns - Use
value_counts()orgroupby().size()to count occurrences of unique combinations - Use
.duplicated(subset=cols)to flag duplicate rows based on specific columns - Use
nunique()to quickly count the number of unique values per column
Related reading
- pandas.factorize on an entire data frame
- pandas.parser.CParserError Error tokenizing data
- Parallel processes in distributed tensorflow
- Parsing one terabyte of text and efficiently counting the number of occurrences of each word
- Parallel Import a python file from sibling folder
- Parse a .py file, read the AST, modify it, then write back the modified source code
- Pattern Detection in Time Series Data
- Pattern recognition in time series
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.