Bird
Raised Fist0
Data Analysis Pythondata~20 mins

nunique() for cardinality in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cardinality Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of nunique() on a DataFrame column
What is the output of the following code snippet?
Data Analysis Python
import pandas as pd

data = {'fruit': ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']}
df = pd.DataFrame(data)

result = df['fruit'].nunique()
print(result)
A3
B6
C4
D2
Attempts:
2 left
💡 Hint
Count how many unique fruit names appear in the list.
❓ data_output
intermediate
2:00remaining
Number of unique values per column
Given the DataFrame below, what is the output of df.nunique()?
Data Analysis Python
import pandas as pd

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

result = df.nunique()
print(result)
A
A    3
B    3
C    2
dtype: int64
B
A    4
B    3
C    2
dtype: int64
C
A    3
B    2
C    2
dtype: int64
D
A    3
B    3
C    3
dtype: int64
Attempts:
2 left
💡 Hint
Count unique values in each column separately.
🔧 Debug
advanced
2:00remaining
Identify the error in using nunique()
What error will this code produce?
Data Analysis Python
import pandas as pd

data = {'numbers': [1, 2, 3, 4]}
df = pd.DataFrame(data)

result = df.nunique(axis=2)
print(result)
ATypeError: axis must be 0 or 1
BValueError: axis 2 is out of bounds for array of dimension 2
CAttributeError: 'DataFrame' object has no attribute 'nunique'
DNo error, prints the number of unique values per row
Attempts:
2 left
💡 Hint
Check the valid axis values for DataFrame methods.
🚀 Application
advanced
2:00remaining
Using nunique() to find columns with high cardinality
You have a DataFrame with many columns. Which code snippet correctly finds columns with more than 10 unique values?
Data Analysis Python
import pandas as pd

# Assume df is predefined

# Find columns with more than 10 unique values
high_card_cols = ?
Ahigh_card_cols = df.columns[df.nunique() < 10].tolist()
Bhigh_card_cols = df.columns[df.nunique(axis=1) > 10].tolist()
Chigh_card_cols = df.columns[df.nunique() > 10].tolist()
Dhigh_card_cols = df.columns[df.nunique(axis=0) < 10].tolist()
Attempts:
2 left
💡 Hint
nunique() by default counts unique values per column.
🧠 Conceptual
expert
2:00remaining
Understanding nunique() behavior with missing values
Consider a DataFrame column with values: [1, 2, 2, None, 3, None]. What is the output of df['col'].nunique(dropna=False)?
Data Analysis Python
import pandas as pd

data = {'col': [1, 2, 2, None, 3, None]}
df = pd.DataFrame(data)

result = df['col'].nunique(dropna=False)
print(result)
A3
B2
C5
D4
Attempts:
2 left
💡 Hint
dropna=False counts NaN as a unique value.

Practice

(1/5)
1. What does the nunique() function do when applied to a pandas DataFrame column?
easy
A. Finds the maximum value in that column
B. Calculates the sum of all values in that column
C. Returns the total number of rows in the DataFrame
D. Counts the number of unique values in that column

Solution

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

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

    Unlike sum or max, nunique() focuses on counting unique entries, not numerical calculations.
  3. Final Answer:

    Counts the number of unique values in that column -> Option D
  4. Quick Check:

    nunique() = unique count [OK]
Hint: Remember: nunique() counts unique items only [OK]
Common Mistakes:
  • Confusing nunique() with count()
  • Thinking it sums values instead of counting unique ones
  • Assuming it returns total rows instead of unique values
2. Which of the following is the correct syntax to count unique values in the 'Age' column of a pandas DataFrame named df?
easy
A. df.nunique('Age')
B. df['Age'].nunique()
C. df.nunique['Age']
D. df.nunique.Age()

Solution

  1. Step 1: Access the column correctly

    To apply nunique() on a column, first select the column using df['Age'].
  2. Step 2: Apply the nunique() method

    Then call nunique() as a method: df['Age'].nunique().
  3. Final Answer:

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

    Correct syntax = df['column'].nunique() [OK]
Hint: Use bracket notation for columns before nunique() [OK]
Common Mistakes:
  • Passing column name as argument to nunique()
  • Using dot notation with parentheses on column name
  • Trying to index nunique like a dictionary
3. Given the DataFrame below, what is the output of df['City'].nunique()?
import pandas as pd
data = {'City': ['Paris', 'London', 'Paris', 'Berlin', 'London', 'Rome']}
df = pd.DataFrame(data)
medium
A. 4
B. 3
C. 5
D. 6

Solution

  1. Step 1: Identify unique cities in the list

    The cities are: 'Paris', 'London', 'Paris', 'Berlin', 'London', 'Rome'. Unique cities are 'Paris', 'London', 'Berlin', and 'Rome'.
  2. Step 2: Count unique cities

    There are 4 unique cities in total.
  3. Final Answer:

    4 -> Option A
  4. Quick Check:

    Unique cities count = 4 [OK]
Hint: Count distinct values ignoring duplicates [OK]
Common Mistakes:
  • Counting all entries instead of unique ones
  • Miscounting duplicates as unique
  • Confusing number of rows with unique count
4. What is wrong with this code snippet if we want to count unique values in the 'Product' column?
import pandas as pd
data = {'Product': ['A', 'B', 'A', 'C']}
df = pd.DataFrame(data)
unique_count = df.nunique('Product')
medium
A. The nunique() method does not take column names as arguments
B. The DataFrame is missing the 'Product' column
C. The nunique() method should be called without parentheses
D. The DataFrame constructor syntax is incorrect

Solution

  1. Step 1: Check how nunique() works on DataFrames

    When called on a DataFrame, nunique() counts unique values for each column and does not accept column names as arguments.
  2. Step 2: Correct way to count unique values in one column

    To count unique values in 'Product', select the column first: df['Product'].nunique().
  3. Final Answer:

    The nunique() method does not take column names as arguments -> Option A
  4. Quick Check:

    nunique() on DataFrame has no column argument [OK]
Hint: Call nunique() on column, not DataFrame with argument [OK]
Common Mistakes:
  • Passing column name as argument to nunique() on DataFrame
  • Calling nunique without parentheses
  • Misunderstanding DataFrame constructor syntax
5. You have a DataFrame df with a column 'Score' containing some missing values (NaN). How do you count unique scores including the missing values as a unique category?
hard
A. df['Score'].count()
B. df['Score'].nunique(dropna=True)
C. df['Score'].nunique(dropna=False)
D. df['Score'].unique()

Solution

  1. Step 1: Understand dropna parameter in nunique()

    By default, nunique() ignores missing values (NaN). Setting dropna=False counts NaN as a unique value.
  2. Step 2: Apply nunique() with dropna=False

    Use df['Score'].nunique(dropna=False) to include NaN in the unique count.
  3. Final Answer:

    df['Score'].nunique(dropna=False) -> Option C
  4. Quick Check:

    Include NaN by setting dropna=False [OK]
Hint: Use dropna=False to count NaN as unique [OK]
Common Mistakes:
  • Ignoring dropna and missing NaN count
  • Using count() which excludes NaN
  • Using unique() without counting length
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