Pandas unique values and unique combinations of multiple columns
Codemia Knowledge Hub ·
For unique combinations of several columns (unique rows), use df[['col1', 'col2']].drop_duplicates() or groupby. For one flat set of every distinct value that appears in any of the columns, use pd.unique() or np.unique() on the stacked values. Decide which of the two you need first, because they answer different questions.
Sample data
Unique combinations of two or more columns
drop_duplicates()
groupby with counts
value_counts on multiple columns
This returns the combinations sorted by frequency:
All distinct values across columns as one set
pd.unique keeps the order of first appearance, while np.unique returns the values sorted.
Unique values in each column
Removing or flagging duplicate combinations
Unique combinations with aggregated values
Mistakes to avoid
- Confusing
unique()withdrop_duplicates():df['col'].unique()returns the unique values of one Series.df[['col1', 'col2']].drop_duplicates()returns unique row combinations. A DataFrame has no.unique()method, so calling it on a multi-column selection raisesAttributeError. .values.ravel()on mixed types: If the columns have different dtypes (for example string and int),.values.ravel()converts everything to object dtype, which can make comparisons behave unexpectedly. Make the column types compatible before combining.- Forgetting
reset_index(drop=True):drop_duplicates()keeps the original index values, leaving gaps (0, 1, 3). If later code expects consecutive indices, call.reset_index(drop=True)afterwards. - NaN and
nunique():nunique()excludes NaN by default. To count it, usedf['col'].nunique(dropna=False). This is whynunique()andlen(unique())can disagree. - Performance on large DataFrames:
drop_duplicates()across many columns hashes every row, which is slow with millions of rows. Sorting first or usinggroupby().first()can be faster on sorted data.
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
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.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 courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.