0
0
Data Analysis Pythondata~20 mins

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

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