📖 Scenario: You work in a company that collects customer feedback. The feedback includes a column for customer satisfaction levels recorded as text labels like 'Low', 'Medium', and 'High'. You want to convert these text labels into a categorical type to save memory and prepare for analysis.
🎯 Goal: Convert a pandas DataFrame column with text labels into a categorical data type.
📋 What You'll Learn
Create a pandas DataFrame with a column named satisfaction containing the exact values: 'Low', 'Medium', 'High', 'Medium', 'Low'.
Create a variable called categories that lists the categories in order: 'Low', 'Medium', 'High'.
Convert the satisfaction column to a categorical type using the categories variable.
Print the satisfaction column's data type after conversion.
💡 Why This Matters
🌍 Real World
Categorical data types save memory and improve performance when working with columns that have repeated text values, like survey responses or product categories.
💼 Career
Data scientists and analysts often convert text columns to categorical types to optimize data storage and prepare data for machine learning models.
Progress0 / 4 steps
1
Create the DataFrame
Create a pandas DataFrame called df with one column named satisfaction containing these exact values in order: 'Low', 'Medium', 'High', 'Medium', 'Low'.
Pandas
Hint
Use pd.DataFrame with a dictionary where the key is 'satisfaction' and the value is the list of satisfaction levels.
2
Define the categories
Create a variable called categories that is a list containing the strings 'Low', 'Medium', and 'High' in this exact order.
Pandas
Hint
Just assign the list ['Low', 'Medium', 'High'] to the variable categories.
3
Convert the column to categorical
Convert the satisfaction column in df to a categorical type using the categories list. Use pd.Categorical with the categories argument and set ordered=True. Assign the result back to df['satisfaction'].
Pandas
Hint
Use pd.Categorical to convert the column and assign it back to df['satisfaction'].
4
Print the data type
Print the data type of the satisfaction column in df using print(df['satisfaction'].dtype).
Pandas
Hint
Use print(df['satisfaction'].dtype) to see the data type after conversion.
Practice
(1/5)
1. What is the main benefit of converting a text column to a categorical type in pandas?
easy
A. It removes duplicate rows from the DataFrame.
B. It changes the text to numbers automatically.
C. It saves memory and speeds up analysis.
D. It sorts the DataFrame by that column.
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 C
Quick Check:
Converting to categorical = Save memory and speed [OK]
Hint: Categorical = less memory + faster analysis [OK]
Common Mistakes:
Thinking it changes text to numbers visibly
Assuming it sorts data automatically
Confusing with removing duplicates
2. Which of the following is the correct syntax to convert a pandas DataFrame column df['color'] to categorical?
easy
A. df['color'] = df['color'].astype('category')
B. df['color'] = pd.to_categorical(df['color'])
C. df['color'] = df['color'].convert('category')
D. df['color'] = df['color'].category()
Solution
Step 1: Recall pandas method for type conversion
The correct method is astype('category') to convert column type.
Step 2: Check each option
df['color'] = df['color'].astype('category') uses astype('category'), which is correct. Others are invalid pandas syntax.
Final Answer:
df['color'] = df['color'].astype('category') -> Option A
Quick Check:
Use astype('category') to convert [OK]
Hint: Use astype('category') to convert columns [OK]
Common Mistakes:
Using non-existent methods like convert() or category()
Trying pd.to_categorical which is not a pandas function
B. astype() does not accept ordered=True argument.
C. pd.Categorical requires categories to be sorted alphabetically.
D. Missing import statement for pandas.
Solution
Step 1: Check astype() method parameters
The astype() method does not accept an ordered parameter.
Step 2: Identify correct way to set ordered
Ordering must be set when creating the categorical with pd.Categorical(..., ordered=True), not via astype.
Final Answer:
astype() does not accept ordered=True argument. -> Option B
Quick Check:
ordered=True only in pd.Categorical, not astype [OK]
Hint: ordered=True only works in pd.Categorical, not astype [OK]
Common Mistakes:
Trying to set ordered in astype()
Assuming categories must be sorted alphabetically
Thinking multiple conversions cause error
5. You have a DataFrame 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?
hard
A. df['status'] = df['status'].astype('category', ordered=True)
print(df['status'].value_counts(sort=False))
B. df['status'] = df['status'].astype('category')
print(df['status'].value_counts())
C. df['status'] = pd.Categorical(df['status'])
print(df['status'].value_counts(sort=True))
D. df['status'] = pd.Categorical(df['status'], categories=['low', 'medium', 'high'], ordered=True)
print(df['status'].value_counts(sort=False))
Solution
Step 1: Convert with ordered categories
Use pd.Categorical with categories=['low', 'medium', 'high'] and ordered=True to set order.
Step 2: Get counts without sorting
Use value_counts(sort=False) to get counts in category order.