Ordered categories in Pandas - Time & Space Complexity
We want to understand how the time needed to work with ordered categories changes as the data grows.
Specifically, how does sorting or comparing ordered categories scale with more data?
Analyze the time complexity of the following code snippet.
import pandas as pd
# Create a categorical column with order
cats = pd.Categorical(["low", "medium", "high", "medium", "low"],
categories=["low", "medium", "high"], ordered=True)
# Create a DataFrame
df = pd.DataFrame({"priority": cats})
# Sort the DataFrame by the ordered category
sorted_df = df.sort_values(by="priority")
This code creates an ordered categorical column and sorts the DataFrame by that column.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the DataFrame rows based on the ordered category column.
- How many times: The sorting algorithm compares elements multiple times, roughly proportional to n log n, where n is the number of rows.
As the number of rows increases, the sorting work grows faster than just adding rows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 comparisons |
| 100 | About 700 comparisons |
| 1000 | About 10,000 comparisons |
Pattern observation: The number of operations grows faster than the number of rows, roughly like n times log n.
Time Complexity: O(n log n)
This means that sorting ordered categories takes more time as data grows, but not as fast as checking every pair.
[X] Wrong: "Sorting ordered categories is just as fast as scanning the data once."
[OK] Correct: Sorting needs multiple comparisons and rearrangements, which take more time than just looking at each item once.
Understanding how sorting ordered categories scales helps you explain data processing steps clearly and shows you know how data size affects performance.
"What if the categories were unordered? How would sorting by that column affect time complexity?"
Practice
ordered=True do when creating a pandas categorical variable?Solution
Step 1: Understand the role of ordered categories
Ordered categories allow pandas to know the sequence of categories, so it can compare them meaningfully.Step 2: Effect of ordered=True
Setting ordered=True tells pandas to treat the categories as having a specific order, enabling operations like greater than or less than.Final Answer:
It defines a natural order for the categories, allowing comparisons. -> Option CQuick Check:
ordered=True means categories have order [OK]
- Thinking it sorts categories automatically
- Assuming it converts categories to numbers
- Believing it removes duplicates
Solution
Step 1: Check parameter order and names
pd.Categorical takes data first, then categories, then ordered flag as keyword arguments.Step 2: Identify correct syntax
pd.Categorical(['low', 'medium', 'high'], categories=['low', 'medium', 'high'], ordered=True) correctly passes data, categories list, and ordered=True in correct order and names.Final Answer:
pd.Categorical(['low', 'medium', 'high'], categories=['low', 'medium', 'high'], ordered=True) -> Option AQuick Check:
Correct syntax uses categories= and ordered=True [OK]
- Passing ordered=True before categories
- Using ordered=False for ordered categories
- Not matching categories list with data
import pandas as pd cats = pd.Categorical(['medium', 'low', 'high'], categories=['low', 'medium', 'high'], ordered=True) print(cats > 'low')
Solution
Step 1: Understand the categories and order
Categories are ordered as low < medium < high.Step 2: Compare each element to 'low'
'medium' > 'low' is True, 'low' > 'low' is False, 'high' > 'low' is True.Final Answer:
[True, False, True] -> Option DQuick Check:
medium and high are greater than low [OK]
- Confusing category order
- Assuming string comparison instead of categorical
- Mixing True/False positions
import pandas as pd cats = pd.Categorical(['low', 'medium', 'high'], categories=['low', 'medium'], ordered=True) print(cats > 'medium')
Solution
Step 1: Check categories vs data
Data contains 'high' but categories only include 'low' and 'medium'.Step 2: Understand effect on comparison
'high' is not in categories, so comparison with 'medium' fails causing error.Final Answer:
The categories list is missing 'high', causing invalid comparison. -> Option BQuick Check:
Data must match categories exactly [OK]
- Thinking ordered=True disallows categories
- Believing '>' is unsupported for ordered categories
- Ignoring missing categories in list
Solution
Step 1: Define ordered categories with correct order
Set categories=['small', 'medium', 'large', 'extra large'] with ordered=True to define natural order.Step 2: Sort DataFrame by the ordered categorical column
Use df.sort_values('size') to sort according to the defined order.Final Answer:
df['size'] = pd.Categorical(df['size'], categories=['small', 'medium', 'large', 'extra large'], ordered=True) df.sort_values('size') -> Option AQuick Check:
Set ordered categories then sort [OK]
- Not specifying categories order
- Using wrong category order
- Trying to sort without ordered categories
Ready to prove it?
Pass the test and this pattern moves unknown
