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'.
Step 2: Count unique values
There are 3 unique cities.
Final Answer:
3 -> Option C
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
Step 1: Check nunique() parameters
The nunique() function in pandas does not support the axis parameter to count unique values row-wise.
Step 2: Understand correct usage
It works column-wise by default. To count unique values per row, a different approach is needed.
Final Answer:
The axis parameter is invalid for nunique() -> Option A
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
Step 1: Understand the goal
We want to count unique cities for each person (grouped by 'Name').
Step 2: Use groupby and nunique correctly
The correct syntax is to group by 'Name' and then apply nunique() on the 'City' column.
Step 3: Check options
df.groupby('Name')['City'].nunique() matches this syntax. Others misuse parameters or group by wrong columns.
Final Answer:
df.groupby('Name')['City'].nunique() -> Option B
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 unknownstrongwhile earning +1 Grip toward your certificate.