0
0
Pandasdata~10 mins

nunique() for unique counts in Pandas - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - nunique() for unique counts
Start with DataFrame
Call nunique()
Count unique values per column or axis
Return counts as Series or scalar
End
The nunique() function counts how many unique values exist in each column or row of a DataFrame and returns those counts.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({
  'A': [1, 2, 2, 3],
  'B': ['x', 'y', 'x', 'z']
})

counts = df.nunique()
This code creates a DataFrame and uses nunique() to count unique values in each column.
Execution Table
StepActionDataFrame Statenunique() Result
1Create DataFrame{'A':[1,2,2,3], 'B':['x','y','x','z']}
2Call df.nunique()Same as step 1Counts unique values per column
3Count unique in column 'A'Values: [1,2,2,3]3 (unique: 1,2,3)
4Count unique in column 'B'Values: ['x','y','x','z']3 (unique: x,y,z)
5Return resultA: 3, B: 3 (as Series)
💡 All columns processed, unique counts returned as Series.
Variable Tracker
VariableStartAfter nunique()
df{'A':[1,2,2,3], 'B':['x','y','x','z']}No change
countsNot definedA: 3, B: 3 (Series)
Key Moments - 2 Insights
Why does nunique() count 3 unique values in column 'A' when there are 4 rows?
Because nunique() counts distinct values, and column 'A' has values 1, 2, 2, 3. The value 2 repeats, so unique values are 1, 2, and 3, totaling 3. See execution_table rows 3 and 5.
What does nunique() return when called without arguments?
It returns a Series with the count of unique values for each column. See execution_table row 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the unique count for column 'B' at step 4?
A2
B3
C4
D1
💡 Hint
Check execution_table row 4 where unique values in column 'B' are counted.
At which step does nunique() return the final counts as a Series?
AStep 5
BStep 2
CStep 3
DStep 4
💡 Hint
Look for the step where the result is returned, see execution_table row 5.
If column 'A' had all unique values, how would the count change in the variable_tracker?
Acounts for 'A' would be 1
Bcounts for 'A' would be 3
Ccounts for 'A' would be 4
Dcounts for 'A' would be 0
💡 Hint
Unique count equals number of distinct values, see variable_tracker for current counts.
Concept Snapshot
pandas.DataFrame.nunique()
Counts unique values per column or row.
Returns a Series with counts.
Default axis=0 (columns).
Useful to find distinct values quickly.
Full Transcript
We start with a DataFrame containing columns 'A' and 'B'. Calling df.nunique() counts how many unique values each column has. For column 'A', values are 1, 2, 2, 3, so unique count is 3. For column 'B', values are 'x', 'y', 'x', 'z', so unique count is also 3. The function returns these counts as a Series. This helps us quickly see how many different values each column contains.