nunique() for cardinality in Data Analysis Python - Time & Space Complexity
We want to understand how the time to count unique values grows as the data size increases.
How does the work change when we have more rows to check for unique items?
Analyze the time complexity of the following code snippet.
import pandas as pd
data = pd.Series([1, 2, 2, 3, 4, 4, 4, 5])
unique_count = data.nunique()
print(unique_count)
This code counts how many different values are in the data series.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element to see if it is unique.
- How many times: Once for each item in the data series.
As the number of items grows, the work grows roughly in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to count unique values grows linearly with the number of items.
[X] Wrong: "Counting unique values is instant no matter how big the data is."
[OK] Correct: The function must look at each item at least once, so bigger data means more work.
Understanding how counting unique items scales helps you explain data processing speed clearly and confidently.
"What if we used a sorted list before counting unique values? How would the time complexity change?"
Practice
nunique() function do when applied to a pandas DataFrame column?Solution
Step 1: Understand the purpose of
Thenunique()nunique()function counts how many distinct or unique values exist in a column.Step 2: Compare with other functions
Unlike sum or max,nunique()focuses on counting unique entries, not numerical calculations.Final Answer:
Counts the number of unique values in that column -> Option DQuick Check:
nunique()= unique count [OK]
nunique() counts unique items only [OK]- Confusing
nunique()withcount() - Thinking it sums values instead of counting unique ones
- Assuming it returns total rows instead of unique values
df?Solution
Step 1: Access the column correctly
To applynunique()on a column, first select the column usingdf['Age'].Step 2: Apply the
Then callnunique()methodnunique()as a method:df['Age'].nunique().Final Answer:
df['Age'].nunique() -> Option BQuick Check:
Correct syntax = df['column'].nunique() [OK]
nunique() [OK]- Passing column name as argument to
nunique() - Using dot notation with parentheses on column name
- Trying to index
nuniquelike a dictionary
df['City'].nunique()?
import pandas as pd
data = {'City': ['Paris', 'London', 'Paris', 'Berlin', 'London', 'Rome']}
df = pd.DataFrame(data)Solution
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'.Step 2: Count unique cities
There are 4 unique cities in total.Final Answer:
4 -> Option AQuick Check:
Unique cities count = 4 [OK]
- Counting all entries instead of unique ones
- Miscounting duplicates as unique
- Confusing number of rows with unique count
import pandas as pd
data = {'Product': ['A', 'B', 'A', 'C']}
df = pd.DataFrame(data)
unique_count = df.nunique('Product')Solution
Step 1: Check how
When called on a DataFrame,nunique()works on DataFramesnunique()counts unique values for each column and does not accept column names as arguments.Step 2: Correct way to count unique values in one column
To count unique values in 'Product', select the column first:df['Product'].nunique().Final Answer:
Thenunique()method does not take column names as arguments -> Option AQuick Check:
nunique()on DataFrame has no column argument [OK]
nunique() on column, not DataFrame with argument [OK]- Passing column name as argument to
nunique()on DataFrame - Calling
nuniquewithout parentheses - Misunderstanding DataFrame constructor syntax
df with a column 'Score' containing some missing values (NaN). How do you count unique scores including the missing values as a unique category?Solution
Step 1: Understand
By default,dropnaparameter innunique()nunique()ignores missing values (NaN). Settingdropna=Falsecounts NaN as a unique value.Step 2: Apply
Usenunique()withdropna=Falsedf['Score'].nunique(dropna=False)to include NaN in the unique count.Final Answer:
df['Score'].nunique(dropna=False) -> Option CQuick Check:
Include NaN by setting dropna=False [OK]
dropna=False to count NaN as unique [OK]- Ignoring
dropnaand missing NaN count - Using
count()which excludes NaN - Using
unique()without counting length
Ready to prove it?
Pass the test and this pattern moves unknown
