value_counts() for distributions in Data Analysis Python - Time & Space Complexity
We want to understand how long it takes to count unique values in data using value_counts().
How does the time change when the data size grows?
Analyze the time complexity of the following code snippet.
import pandas as pd
data = pd.Series(["apple", "banana", "apple", "orange", "banana", "banana"])
counts = data.value_counts()
print(counts)
This code counts how many times each unique fruit appears in the list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each item in the data once to count occurrences.
- How many times: Exactly once for each of the n items in the data.
As the data size grows, the counting work grows roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows in a straight line with the input size.
Time Complexity: O(n)
This means the time to count values grows directly with the number of items.
[X] Wrong: "Counting unique values takes longer if there are many unique items than if there are few."
[OK] Correct: The main work is scanning all items once, so the total time depends mostly on data size, not how many unique values there are.
Knowing how counting operations scale helps you explain performance clearly and shows you understand data processing basics.
"What if the data was already sorted? How would that affect the time complexity of value_counts()?"
Practice
value_counts() function do when applied to a pandas Series?Solution
Step 1: Understand the purpose of
This function counts each unique value's frequency in a pandas Series.value_counts()Step 2: Compare with other options
Sorting, averaging, or removing duplicates are different operations not done byvalue_counts().Final Answer:
Counts how many times each unique value appears in the Series -> Option BQuick Check:
value_counts()= counts unique values [OK]
- Thinking it sorts values instead of counting
- Confusing it with mean or average calculation
- Assuming it removes duplicates instead of counting
data?Solution
Step 1: Recall the parameter for percentage in
The correct parameter isvalue_counts()normalize=Trueto get proportions.Step 2: Check other options for correctness
Options withpercentorpercentageare invalid parameters and cause errors.Final Answer:
data.value_counts(normalize=True) -> Option CQuick Check:
Usenormalize=Truefor percentages [OK]
- Using wrong parameter names like percent or percentage
- Forgetting to set normalize=True for percentages
- Confusing normalize=False with percentage output
colors = pd.Series(['red', 'blue', 'red', 'green', 'blue', 'blue']), what is the output of colors.value_counts()?Solution
Step 1: Count each color's occurrences
'red' appears 2 times, 'blue' 3 times, 'green' 1 time.Step 2: Understand
It sorts counts descending by default, so 'blue' (3), 'red' (2), 'green' (1).value_counts()output orderFinal Answer:
{'blue': 3, 'red': 2, 'green': 1} -> Option AQuick Check:
Counts sorted descending = {'blue':3,'red':2,'green':1} [OK]
- Ignoring the default descending sort order
- Mixing up counts of 'red' and 'blue'
- Assuming output is unordered or sorted alphabetically
df['Category'] is a pandas Series?df.value_counts(normalize=True)
Solution
Step 1: Identify the object
value_counts()is called ondfis a DataFrame, butvalue_counts()works on Series, not DataFrame directly.Step 2: Correct usage for counting a column
Usedf['Category'].value_counts(normalize=True)to count values in that column.Final Answer:
It should bedf['Category'].value_counts(normalize=True)to count values in the column -> Option AQuick Check:
value_counts()needs a Series, not DataFrame [OK]
- Calling value_counts() directly on DataFrame
- Confusing DataFrame and Series methods
- Thinking normalize is invalid parameter
responses with values: ['yes', 'no', 'yes', 'maybe', 'no', 'yes', 'no', 'maybe', 'yes', 'no'].How do you get the percentage distribution of each response rounded to 2 decimals?
Solution
Step 1: Use
This returns the relative frequencies as decimals.value_counts(normalize=True)to get percentagesStep 2: Apply
Chaininground(2)to round percentages to 2 decimals.round(2)rounds the decimal values properly.Final Answer:
responses.value_counts(normalize=True).round(2) -> Option DQuick Check:
Normalize then round decimals = responses.value_counts(normalize=True).round(2) [OK]
- Using invalid parameter percent=True
- Calling normalize() as a method instead of parameter
- Rounding counts instead of percentages
Ready to prove it?
Pass the test and this pattern moves unknown
