Why categorical type matters in Pandas - Performance Analysis
We want to see how using the categorical type in pandas affects the time it takes to do operations.
How does changing data type change the work pandas must do?
Analyze the time complexity of the following code snippet.
import pandas as pd
# Create a large DataFrame with repeated categories
n = 100000
categories = ['apple', 'banana', 'cherry']
data = pd.DataFrame({
'fruit': ['apple', 'banana', 'cherry'] * (n // 3)
})
# Convert to categorical type
cat_data = data['fruit'].astype('category')
# Count the occurrences of each category
counts = cat_data.value_counts()
This code creates a large list of fruits, converts it to a categorical type, and counts how many times each fruit appears.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Counting occurrences by scanning all items in the column.
- How many times: Once over all n rows to count.
Counting needs to look at each item once, so work grows as the list grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to count grows in a straight line as the data size grows.
[X] Wrong: "Using categorical type makes counting instant or constant time."
[OK] Correct: Even with categories, pandas must still look at every item once to count them all.
Understanding how data types affect operation speed helps you write faster code and explain your choices clearly.
"What if we had many more unique categories instead of just a few? How would the time complexity change?"
Practice
categorical data type in pandas helpful when you have a column with many repeated text values?Solution
Step 1: Understand memory usage of text data
Repeated text values take more memory because each string is stored separately.Step 2: How categorical type optimizes memory
Categorical type stores unique values once and uses codes to represent them, saving memory.Final Answer:
It saves memory by storing repeated values efficiently. -> Option CQuick Check:
Memory saving = A [OK]
- Thinking categorical sorts data automatically
- Believing categorical removes duplicates
- Assuming categorical converts text to numbers for math
df['color'] to categorical type?Solution
Step 1: Identify correct pandas method for type conversion
Theastype()method is used to change data types in pandas.Step 2: Check correct argument for categorical type
Passing the string 'category' toastype()converts the column to categorical type.Final Answer:
df['color'] = df['color'].astype('category') -> Option DQuick Check:
astype('category') = D [OK]
- Using pd.to_numeric for text columns
- Trying astype('string') instead of 'category'
- Using a non-existent convert() method
import pandas as pd
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
df = pd.DataFrame({'color': colors})
df['color'] = df['color'].astype('category')
print(df['color'].cat.codes.tolist())What is the output?
Solution
Step 1: Understand category codes assignment
Categories are assigned codes in alphabetical order: 'blue' = 0, 'green' = 1, 'red' = 2.Step 2: Check actual categories order
By default, pandas assigns categories in alphabetical order, not order of appearance.Step 3: Map colors to codes
Mapping list: 'red'->2, 'blue'->0, 'red'->2, 'green'->1, 'blue'->0, 'blue'->0.Final Answer:
[2, 0, 2, 1, 0, 0] -> Option AQuick Check:
Category codes = A [OK]
- Assuming order of appearance for codes
- Thinking codes start at 1
- Confusing category codes with original values
df['size'] = ['small', 'medium', 'large', 'medium']
df['size'] = df['size'].astype('category')
df['size'] = df['size'].cat.set_categories(['small', 'medium', 'large'], ordered=True)
print(df['size'].sort_values())But the output is not sorted as expected. What is the likely problem?
Solution
Step 1: Understand what
It sets the categories and order but does not reorder the actual data.set_categoriesdoesStep 2: How sorting works on ordered categorical
Sorting uses the category order, butsort_values()sorts rows, not the category levels themselves.Final Answer:
Theset_categoriesmethod does not sort the data. -> Option AQuick Check:
set_categories() sets order, doesn't sort data [OK]
- Expecting set_categories to reorder data automatically
- Thinking sort_values fails on categorical columns
- Trying to convert to string before sorting
'city' containing many repeated city names. You want to reduce memory usage and speed up filtering for cities in a specific order: 'New York', 'Los Angeles', 'Chicago'. Which approach is best?Solution
Step 1: Why use categorical with order
Ordered categorical saves memory and allows meaningful sorting/filtering by specified city order.Step 2: Why other options are less suitable
Keeping strings uses more memory; numeric codes without categories lose order meaning; removing duplicates loses data.Final Answer:
Convert 'city' to categorical with ordered categories: ['New York', 'Los Angeles', 'Chicago'] -> Option BQuick Check:
Ordered categorical = A [OK]
- Not setting categories order
- Using numeric codes without categories
- Removing duplicates instead of optimizing type
Ready to prove it?
Pass the test and this pattern moves unknown
