Converting to categorical in Pandas - Time & Space Complexity
We want to understand how long it takes to convert a column in a DataFrame to a categorical type.
How does the time needed change when the data size grows?
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({
'color': ['red', 'blue', 'green', 'blue', 'red'] * 1000
})
df['color_cat'] = df['color'].astype('category')
This code creates a DataFrame with repeated color names and converts the 'color' column to a categorical type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each value in the column to assign category codes.
- How many times: Once for each row in the column (n times).
As the number of rows increases, the time to convert grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and assignments |
| 100 | About 100 checks and assignments |
| 1000 | About 1000 checks and assignments |
Pattern observation: Doubling the input roughly doubles the work needed.
Time Complexity: O(n)
This means the time to convert grows linearly with the number of rows in the column.
[X] Wrong: "Converting to categorical is instant no matter the data size."
[OK] Correct: The operation must look at each value to assign categories, so it takes longer with more data.
Understanding how data type conversions scale helps you write efficient data processing code in real projects.
"What if the column already has only a few unique values? How would that affect the time complexity?"
Practice
Solution
Step 1: Understand what categorical type does
Converting text to categorical stores repeated values efficiently, saving memory.Step 2: Recognize impact on analysis speed
Operations on categorical data are faster because pandas uses codes internally.Final Answer:
It saves memory and speeds up analysis. -> Option CQuick Check:
Converting to categorical = Save memory and speed [OK]
- Thinking it changes text to numbers visibly
- Assuming it sorts data automatically
- Confusing with removing duplicates
df['color'] to categorical?Solution
Step 1: Recall pandas method for type conversion
The correct method isastype('category')to convert column type.Step 2: Check each option
df['color'] = df['color'].astype('category') usesastype('category'), which is correct. Others are invalid pandas syntax.Final Answer:
df['color'] = df['color'].astype('category') -> Option AQuick Check:
Use astype('category') to convert [OK]
- Using non-existent methods like convert() or category()
- Trying pd.to_categorical which is not a pandas function
- Missing quotes around 'category'
import pandas as pd
df = pd.DataFrame({'size': ['S', 'M', 'L', 'M', 'S']})
df['size'] = pd.Categorical(df['size'], categories=['S', 'M', 'L'], ordered=True)
print(df['size'].dtype)What will be the output?
Solution
Step 1: Understand pd.Categorical usage
Usingpd.Categoricalconverts the column to categorical dtype with order.Step 2: Check dtype after conversion
The dtype of the column becomescategory, not object or string.Final Answer:
category -> Option AQuick Check:
pd.Categorical sets dtype to category [OK]
- Expecting dtype to remain object
- Confusing category with string dtype
- Thinking dtype becomes int64
import pandas as pd
df = pd.DataFrame({'grade': ['A', 'B', 'C', 'B', 'A']})
df['grade'] = pd.Categorical(df['grade'], categories=['A', 'B', 'C'])
df['grade'] = df['grade'].astype('category', ordered=True)Solution
Step 1: Check astype() method parameters
Theastype()method does not accept anorderedparameter.Step 2: Identify correct way to set ordered
Ordering must be set when creating the categorical withpd.Categorical(..., ordered=True), not via astype.Final Answer:
astype() does not accept ordered=True argument. -> Option BQuick Check:
ordered=True only in pd.Categorical, not astype [OK]
- Trying to set ordered in astype()
- Assuming categories must be sorted alphabetically
- Thinking multiple conversions cause error
df with a column 'status' containing repeated text values: 'low', 'medium', 'high'. You want to convert it to a categorical type with the order low < medium < high, and then get the counts of each category in order. Which code snippet correctly does this?Solution
Step 1: Convert with ordered categories
Usepd.Categoricalwithcategories=['low', 'medium', 'high']andordered=Trueto set order.Step 2: Get counts without sorting
Usevalue_counts(sort=False)to get counts in category order.Final Answer:
df['status'] = pd.Categorical(df['status'], categories=['low', 'medium', 'high'], ordered=True) print(df['status'].value_counts(sort=False)) -> Option DQuick Check:
pd.Categorical + ordered + value_counts(sort=False) = correct [OK]
- Using astype('category') without order
- Not setting ordered=True for category order
- Using value_counts() without sort=False loses order
Ready to prove it?
Pass the test and this pattern moves unknown
