Encoding categorical variables in Data Analysis Python - Time & Space Complexity
When we convert categories into numbers, we want to know how long it takes as data grows.
How does the time needed change when we have more data or more categories?
Analyze the time complexity of the following code snippet.
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
data = pd.DataFrame({
'color': ['red', 'blue', 'green', 'blue', 'red'] * 1000
})
encoder = OneHotEncoder(sparse_output=False)
encoded = encoder.fit_transform(data[['color']])
This code turns a list of colors into a set of columns with 1s and 0s for each color.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each row to assign a 1 or 0 for each category.
- How many times: Once for each data row times the number of unique categories.
As the number of rows or categories grows, the work grows too.
| Input Size (n rows) | Approx. Operations |
|---|---|
| 10 | 10 x number of categories |
| 100 | 100 x number of categories |
| 1000 | 1000 x number of categories |
Pattern observation: The work grows in a straight line with the number of rows and categories.
Time Complexity: O(n x k)
This means the time grows with both the number of data rows and the number of unique categories.
[X] Wrong: "Encoding time depends only on the number of rows."
[OK] Correct: Because each row must be checked against all categories, more categories mean more work.
Understanding how encoding scales helps you explain data preparation steps clearly and shows you think about efficiency.
"What if we used label encoding instead of one-hot encoding? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of encoding
Encoding changes categories like 'red', 'blue' into numbers so computers can understand them.Step 2: Identify the purpose in data science
Machine learning models require numbers, so encoding helps prepare data for these models.Final Answer:
To convert categories into numbers so algorithms can process them -> Option CQuick Check:
Encoding = convert categories to numbers [OK]
- Confusing encoding with data cleaning
- Thinking encoding normalizes data
- Assuming encoding is for visualization
Solution
Step 1: Recognize label encoding syntax
LabelEncoder from sklearn.preprocessing is used with fit_transform on a column.Step 2: Match code to correct usage
from sklearn.preprocessing import LabelEncoder le = LabelEncoder() data['color_encoded'] = le.fit_transform(data['color']) correctly imports LabelEncoder, creates an instance, and applies fit_transform to the 'color' column.Final Answer:
from sklearn.preprocessing import LabelEncoder le = LabelEncoder() data['color_encoded'] = le.fit_transform(data['color']) -> Option AQuick Check:
LabelEncoder usage = from sklearn.preprocessing import LabelEncoder le = LabelEncoder() data['color_encoded'] = le.fit_transform(data['color']) [OK]
- Using OneHotEncoder instead of LabelEncoder
- Trying to assign get_dummies output directly to one column
- Forgetting to import LabelEncoder
print(encoded_df)?
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
data = pd.DataFrame({'fruit': ['apple', 'banana', 'apple', 'orange']})
encoder = OneHotEncoder(sparse=False)
encoded_array = encoder.fit_transform(data[['fruit']])
encoded_df = pd.DataFrame(encoded_array, columns=encoder.categories_[0])
print(encoded_df)Solution
Step 1: Understand OneHotEncoder output
OneHotEncoder creates separate columns for each category with 1 or 0 indicating presence.Step 2: Check code behavior
Encoded array has shape (4,3) for 'apple', 'banana', 'orange'. DataFrame columns are set to these categories.Final Answer:
A DataFrame with columns 'apple', 'banana', 'orange' containing 1s and 0s indicating fruit presence -> Option BQuick Check:
OneHotEncoder output = separate 0/1 columns [OK]
- Expecting a single column with numbers
- Thinking OneHotEncoder fails on strings
- Assuming original column stays in encoded_df
from sklearn.preprocessing import LabelEncoder
data = pd.DataFrame({'color': ['red', 'blue', 'green']})
le = LabelEncoder()
encoded = le.fit_transform(data['color'])
print(encoded)Solution
Step 1: Check imports and dependencies
The code uses pd.DataFrame without importing pandas, causing NameError: name 'pd' is not defined.Step 2: Fix by adding the import
Add 'import pandas as pd' at the beginning, before defining data.Final Answer:
Missing import for pandas; add 'import pandas as pd' -> Option DQuick Check:
Missing pandas import for pd.DataFrame [OK]
- Not importing pandas before using pd.DataFrame
- Confusing LabelEncoder with OneHotEncoder
- Ignoring data structure requirements
Solution
Step 1: Understand the need to preserve order
Since 'small' < 'medium' < 'large', encoding must respect this order.Step 2: Use pandas Categorical with ordered=True
Creating an ordered categorical allows converting categories to codes that reflect the order.Step 3: Convert ordered categorical to codes
Codes will be 0 for 'small', 1 for 'medium', 2 for 'large' as desired.Final Answer:
Use pandas Categorical with ordered=True and then convert to codes -> Option AQuick Check:
Ordered categorical preserves order in encoding [OK]
- Using LabelEncoder which ignores order
- Using OneHotEncoder which loses order info
- Replacing categories without defining order
Ready to prove it?
Pass the test and this pattern moves unknown
