Bird
Raised Fist0
Pandasdata~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the nunique() function do in pandas?
easy
A. Sorts the values in ascending order
B. Calculates the sum of all values in a DataFrame
C. Replaces missing values with zero
D. Counts the number of unique values in a Series or DataFrame column

Solution

  1. Step 1: Understand the purpose of nunique()

    The nunique() function counts how many different (unique) values exist in a pandas Series or DataFrame column.
  2. Step 2: Compare with other functions

    Other options describe sum, sorting, or filling missing values, which are not what nunique() does.
  3. Final Answer:

    Counts the number of unique values in a Series or DataFrame column -> Option D
  4. Quick Check:

    nunique() = unique count [OK]
Hint: Remember: 'nunique' means 'number of unique' [OK]
Common Mistakes:
  • Confusing with sum() function
  • Thinking it sorts data
  • Assuming it fills missing values
2. Which of the following is the correct syntax to count unique values in the 'Age' column of a DataFrame named df?
easy
A. df['Age'].nunique()
B. df.nunique('Age')
C. df.nunique['Age']
D. df.nunique.Age()

Solution

  1. Step 1: Identify correct method call on a column

    To count unique values in a specific column, select the column first with df['Age'], then call nunique().
  2. Step 2: Check syntax of options

    df['Age'].nunique() uses correct syntax: df['Age'].nunique(). Other options misuse parentheses or indexing.
  3. Final Answer:

    df['Age'].nunique() -> Option A
  4. Quick Check:

    Use df['column'].nunique() for unique count [OK]
Hint: Select column first, then call nunique() [OK]
Common Mistakes:
  • Passing column name as argument to nunique()
  • Using dot notation with parentheses incorrectly
  • Trying to index nunique as if a dictionary
3. Given the DataFrame:
import pandas as pd
data = {'City': ['NY', 'LA', 'NY', 'Chicago', 'LA', 'NY'], 'Score': [10, 20, 10, 30, 20, 40]}
df = pd.DataFrame(data)
print(df['City'].nunique())

What is the output?
medium
A. 4
B. 6
C. 3
D. 2

Solution

  1. Step 1: Identify unique cities in the 'City' column

    The cities are ['NY', 'LA', 'NY', 'Chicago', 'LA', 'NY']. Unique values are 'NY', 'LA', and 'Chicago'.
  2. Step 2: Count unique values

    There are 3 unique cities.
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    Unique cities count = 3 [OK]
Hint: Count distinct city names ignoring repeats [OK]
Common Mistakes:
  • Counting total rows instead of unique values
  • Including duplicates in count
  • Confusing with number of columns
4. You run this code:
import pandas as pd
data = {'A': [1, 2, 2, 3], 'B': [4, 4, 5, 6]}
df = pd.DataFrame(data)
print(df['A'].nunique(axis=1))

But it gives an error. What is the problem?
medium
A. The axis parameter is invalid for nunique()
B. nunique() cannot be used on DataFrames
C. The DataFrame has duplicate values causing error
D. Missing parentheses after nunique

Solution

  1. Step 1: Check nunique() parameters

    The nunique() function in pandas does not support the axis parameter to count unique values row-wise.
  2. Step 2: Understand correct usage

    It works column-wise by default. To count unique values per row, a different approach is needed.
  3. Final Answer:

    The axis parameter is invalid for nunique() -> Option A
  4. Quick Check:

    nunique() has no axis argument [OK]
Hint: Remember: nunique() counts column-wise only [OK]
Common Mistakes:
  • Trying to use axis=1 with nunique()
  • Assuming nunique() works row-wise by default
  • Confusing with other functions that accept axis
5. You have a DataFrame df with columns 'Name', 'City', and 'Age'. You want to find how many unique cities each person has appeared in, but the data has multiple rows per person. Which code correctly counts unique cities per 'Name'?
hard
A. df['City'].nunique(groupby='Name')
B. df.groupby('Name')['City'].nunique()
C. df.nunique('City', by='Name')
D. df.groupby('City')['Name'].nunique()

Solution

  1. Step 1: Understand the goal

    We want to count unique cities for each person (grouped by 'Name').
  2. Step 2: Use groupby and nunique correctly

    The correct syntax is to group by 'Name' and then apply nunique() on the 'City' column.
  3. Step 3: Check options

    df.groupby('Name')['City'].nunique() matches this syntax. Others misuse parameters or group by wrong columns.
  4. Final Answer:

    df.groupby('Name')['City'].nunique() -> Option B
  5. Quick Check:

    Group by 'Name', then count unique 'City' [OK]
Hint: Group by person, then count unique cities with nunique() [OK]
Common Mistakes:
  • Using nunique() without groupby
  • Passing wrong parameters to nunique()
  • Grouping by 'City' instead of 'Name'
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard