nunique() for unique counts in Pandas - Time & Space Complexity
We want to understand how the time needed to count unique values changes as the data grows.
How does pandas' nunique() method scale with bigger data?
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 2, 3, 4, 4, 4, 5]
})
unique_count = df['A'].nunique()
This code counts how many unique values are in column 'A' of the DataFrame.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: pandas scans each value in the column once to check uniqueness.
- How many times: It goes through all
nrows exactly one time.
As the number of rows grows, the time to count unique values grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows linearly as the data size increases.
Time Complexity: O(n)
This means the time to count unique values grows in a straight line with the number of rows.
[X] Wrong: "Counting unique values is instant no matter how big the data is."
[OK] Correct: pandas must look at each value to know if it is new or repeated, so bigger data takes more time.
Understanding how counting unique values scales helps you explain data processing speed clearly and confidently.
"What if we used nunique() on multiple columns at once? How would the time complexity change?"
Practice
nunique() function do in pandas?Solution
Step 1: Understand the purpose of
Thenunique()nunique()function counts how many different (unique) values exist in a pandas Series or DataFrame column.Step 2: Compare with other functions
Other options describe sum, sorting, or filling missing values, which are not whatnunique()does.Final Answer:
Counts the number of unique values in a Series or DataFrame column -> Option DQuick Check:
nunique()= unique count [OK]
- Confusing with sum() function
- Thinking it sorts data
- Assuming it fills missing values
df?Solution
Step 1: Identify correct method call on a column
To count unique values in a specific column, select the column first withdf['Age'], then callnunique().Step 2: Check syntax of options
df['Age'].nunique() uses correct syntax:df['Age'].nunique(). Other options misuse parentheses or indexing.Final Answer:
df['Age'].nunique() -> Option AQuick Check:
Usedf['column'].nunique()for unique count [OK]
nunique() [OK]- Passing column name as argument to
nunique() - Using dot notation with parentheses incorrectly
- Trying to index
nuniqueas if a dictionary
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?
Solution
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 CQuick Check:
Unique cities count = 3 [OK]
- Counting total rows instead of unique values
- Including duplicates in count
- Confusing with number of columns
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?
Solution
Step 1: Check
Thenunique()parametersnunique()function in pandas does not support theaxisparameter 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:
Theaxisparameter is invalid fornunique()-> Option AQuick Check:
nunique()has noaxisargument [OK]
nunique() counts column-wise only [OK]- Trying to use
axis=1withnunique() - Assuming
nunique()works row-wise by default - Confusing with other functions that accept
axis
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'?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 applynunique()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 BQuick Check:
Group by 'Name', then count unique 'City' [OK]
nunique() [OK]- Using
nunique()without groupby - Passing wrong parameters to
nunique() - Grouping by 'City' instead of 'Name'
Ready to prove it?
Pass the test and this pattern moves unknown
