Adding and removing categories in Pandas - Time & Space Complexity
We want to understand how the time needed changes when we add or remove categories in a pandas categorical column.
How does the work grow as the number of categories or data size grows?
Analyze the time complexity of the following code snippet.
import pandas as pd
# Create a categorical column
cat = pd.Categorical(["a", "b", "a", "c"])
# Add a new category
cat = cat.add_categories(["d"])
# Remove a category
cat = cat.remove_categories(["b"])
This code creates a categorical column, then adds a new category, and finally removes an existing category.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Updating the internal categories list and mapping data to new categories.
- How many times: The operations scan through the categories and sometimes the data values once each.
When adding or removing categories, pandas updates the list of categories and may check data values to adjust mappings.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 categories, 1000 data points | Operations scale with categories and data size, roughly scanning categories and data once. |
| 100 categories, 10,000 data points | Operations increase roughly 10 times, scanning more categories and data. |
| 1000 categories, 100,000 data points | Operations increase roughly 100 times, scanning all categories and data. |
Pattern observation: The work grows roughly linearly with the number of categories and data points.
Time Complexity: O(n + k)
This means the time grows linearly with the number of data points (n) plus the number of categories (k).
[X] Wrong: "Adding or removing categories is instant and does not depend on data size."
[OK] Correct: Pandas must update category mappings and sometimes check all data points, so time depends on both categories and data size.
Understanding how operations scale with data size and categories helps you explain performance in real data tasks clearly and confidently.
"What if we add multiple categories at once instead of one by one? How would the time complexity change?"
Practice
add_categories() method do in pandas categorical data?Solution
Step 1: Understand the purpose of
This method is used to add new possible categories to a pandas categorical column without changing existing data.add_categories()Step 2: Differentiate from other methods
Unlikeremove_categories()which removes categories,add_categories()only adds new ones.Final Answer:
It adds new possible categories to an existing categorical column. -> Option CQuick Check:
add_categories()adds categories [OK]
- Confusing add_categories with remove_categories
- Thinking it changes existing data values
- Assuming it renames categories
df['color']?Solution
Step 1: Recall the correct method name
The pandas method to remove categories isremove_categories().Step 2: Match the syntax with the method
df['color'].remove_categories(['red', 'blue']) usesremove_categories()correctly on the categorical column.Final Answer:
df['color'].remove_categories(['red', 'blue']) -> Option AQuick Check:
Useremove_categories()to remove categories [OK]
- Using non-existent methods like drop_categories
- Confusing remove_categories with add_categories
- Trying to remove categories with pop or delete
import pandas as pd cat = pd.Categorical(['apple', 'banana', 'apple'], categories=['apple', 'banana', 'cherry']) cat2 = cat.remove_categories(['banana']) print(cat2)
What will be the output?
Solution
Step 1: Understand remove_categories effect on data
Removing 'banana' category replaces all 'banana' values with NaN and removes 'banana' from categories.Step 2: Analyze the printed output
Values become ['apple', NaN, 'apple'] and categories become ['apple', 'cherry'] with length 2.Final Answer:
[apple, NaN, apple] Categories (2, object): [apple, cherry] -> Option AQuick Check:
Removed category replaced by NaN [OK]
- Expecting removed category values to stay unchanged
- Thinking categories length remains same
- Confusing categories list after removal
import pandas as pd
cat = pd.Categorical(['dog', 'cat', 'bird'], categories=['dog', 'cat', 'bird'])
cat = cat.add_categories('fish')
cat = cat.remove_categories('cat')What is the error in this code?
Solution
Step 1: Check method argument types
remove_categories()requires a list or iterable of categories to remove, not a single string.Step 2: Identify the error cause
Passing 'cat' as a string causes a TypeError or unexpected behavior.Final Answer:
remove_categories expects a list, not a string. -> Option DQuick Check:
Pass list to remove_categories [OK]
- Passing single string instead of list to remove_categories
- Thinking add_categories can't add one item
- Assuming chaining methods is invalid
df['status'] with categories ['new', 'in_progress', 'done']. You want to add a new category 'archived' and remove 'new' without losing data for other rows. Which sequence of commands achieves this correctly?Solution
Step 1: Add new category before removing
Adding 'archived' first ensures it exists as a valid category before removal.Step 2: Remove 'new' category properly
Removing 'new' replaces its values with NaN, so do this after adding new category and assign back to column.Step 3: Assign results back to the column
Both methods return new categorical objects, so assign back todf['status'].Final Answer:
df['status'] = df['status'].add_categories(['archived']) df['status'] = df['status'].remove_categories(['new']) -> Option BQuick Check:
Add then remove, assign back [OK]
- Removing category before adding new one
- Not assigning back to the DataFrame column
- Passing string instead of list to methods
Ready to prove it?
Pass the test and this pattern moves unknown
