Category codes and labels in Pandas - Time & Space Complexity
We want to understand how the time needed to get category codes and labels changes as the data grows.
How does the work grow when we have more data rows?
Analyze the time complexity of the following code snippet.
import pandas as pd
# Create a categorical column
cats = pd.Categorical(['apple', 'banana', 'apple', 'orange', 'banana'])
# Get the integer codes for categories
codes = cats.codes
# Get the category labels
labels = cats.categories
This code creates a categorical data column, then extracts the integer codes and the category labels.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Assigning codes to each data row by matching its category.
- How many times: Once for each row in the data (n times).
As the number of rows grows, the work to assign codes grows roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 code assignments |
| 100 | About 100 code assignments |
| 1000 | About 1000 code assignments |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to get codes grows in a straight line as the data gets bigger.
[X] Wrong: "Getting category codes is instant no matter how big the data is."
[OK] Correct: Even though categories are fixed, assigning codes must check each row, so time grows with data size.
Understanding how category codes work helps you explain data processing speed clearly, a useful skill in real projects and interviews.
"What if we had many more unique categories? How would that affect the time complexity of getting codes?"
Practice
cat.codes show in a pandas categorical Series?Solution
Step 1: Understand what
cat.codesreturnscat.codesgives the integer codes for each category in the Series, replacing repeated text with numbers.Step 2: Differentiate from
cat.categoriescat.categoriesshows the text labels, not the codes.Final Answer:
The numeric codes representing each category -> Option BQuick Check:
cat.codes= numeric codes [OK]
- Confusing codes with category labels
- Thinking codes show counts
- Assuming codes show data type
s?Solution
Step 1: Recall the attribute for category labels
The category labels are accessed viacat.categorieson the Series.Step 2: Check the options for correct syntax
s.cat.categoriesis the correct syntax;s.categoriesis invalid, andcat.labelsdoes not exist.Final Answer:
s.cat.categories-> Option AQuick Check:
Category labels =s.cat.categories[OK]
cat.categories to get labels, not just categories [OK]- Using
s.categoriesinstead ofs.cat.categories - Confusing
cat.codeswith labels - Trying to use non-existent
cat.labels
import pandas as pd s = pd.Series(['apple', 'banana', 'apple', 'orange'], dtype='category') print(s.cat.codes.tolist())
What is the output?
Solution
Step 1: Identify categories and their order
Categories are sorted alphabetically by default: ['apple', 'banana', 'orange'] with codes 0,1,2 respectively.Step 2: Map each value to its code
'apple' -> 0, 'banana' -> 1, 'apple' -> 0, 'orange' -> 2, so the list is [0, 1, 0, 2].Final Answer:
[0, 1, 0, 2] -> Option AQuick Check:
Alphabetical categories -> codes match [OK]
- Assuming codes start at 1 instead of 0
- Ignoring alphabetical sorting of categories
- Mixing up category order
import pandas as pd s = pd.Series(['cat', 'dog', 'cat'], dtype='category') s.cat.categories = ['dog', 'cat'] print(s.cat.codes.tolist())
Solution
Step 1: Understand category assignment rules
Assigning tocat.categoriesredefines the labels for existing codes without changing the codes or raising errors, as long as new list has same length and unique values.Step 2: Trace execution
Original categories ['cat', 'dog'], codes [0,1,0]. New ['dog', 'cat'] same length/unique, codes unchanged, prints [0, 1, 0].Final Answer:
The code will run without errors and print [0, 1, 0] -> Option DQuick Check:
New categories redefine code labels, codes unchanged [OK]
cat.categories changes labels but keeps codes intact [OK]- Thinking reordering causes ValueError
- Expecting codes to adjust to new order like [1, 0, 1]
- Assuming categories must stay alphabetical
s with categories ['low', 'medium', 'high']. You want to rename the categories to ['L', 'M', 'H'] without changing the data. Which code correctly returns the renamed Series?Solution
Step 1: Understand how to rename categories
The methodcat.rename_categories()returns a new Series with renamed categories without changing data codes.Step 2: Check other options for correctness
Direct assignment tocat.categoriesworks but can cause errors if not careful;cat.categories.rename()is invalid;rename_categories()is not a Series method.Final Answer:
s.cat.rename_categories(['L', 'M', 'H'])-> Option CQuick Check:
Usecat.rename_categories()to rename safely [OK]
cat.rename_categories() to rename categories safely [OK]- Trying to rename categories by invalid methods
- Directly assigning categories without matching length
- Confusing Series methods with cat accessor methods
Ready to prove it?
Pass the test and this pattern moves unknown
