Using categorical data type saves memory and speeds up analysis when working with repeated text values.
Categorical data type optimization in Data Analysis Python
df['column_name'] = df['column_name'].astype('category')
astype('category') to convert a column to categorical type.df['color'] = df['color'].astype('category')
df['city'] = df['city'].astype('category') print(df['city'].cat.categories)
df['size'] = pd.Categorical(df['size'], categories=['small', 'medium', 'large'], ordered=True)
This code shows how converting a text column to categorical reduces memory and lists the unique categories.
import pandas as pd # Create a sample DataFrame with repeated text values data = {'color': ['red', 'blue', 'red', 'green', 'blue', 'blue', 'red']} df = pd.DataFrame(data) # Check memory usage before conversion mem_before = df.memory_usage(deep=True).sum() # Convert 'color' column to categorical df['color'] = df['color'].astype('category') # Check memory usage after conversion mem_after = df.memory_usage(deep=True).sum() # Show categories and memory usage difference print('Categories:', df['color'].cat.categories) print(f'Memory before: {mem_before} bytes') print(f'Memory after: {mem_after} bytes')
Categorical data is best for columns with many repeated values.
Ordered categories allow comparisons like less than or greater than.
Converting back to string is easy with astype(str).
Categorical type saves memory by storing unique values once.
Use astype('category') to convert columns.
It speeds up filtering and grouping operations.
Practice
What is the main benefit of converting a DataFrame column to category type in pandas?
Solution
Step 1: Understand what categorical type does
The categorical type stores unique values only once and uses codes internally, saving memory.Step 2: Compare with other options
Sorting, converting to strings, or removing missing values are not automatic effects of categorical conversion.Final Answer:
It reduces memory usage by storing unique values once -> Option AQuick Check:
Categorical type = Memory saving [OK]
- Thinking it sorts values automatically
- Confusing with string conversion
- Assuming it removes missing data
Which of the following is the correct syntax to convert a pandas DataFrame column df['color'] to categorical type?
import pandas as pd
df = pd.DataFrame({'color': ['red', 'blue', 'red', 'green']})Solution
Step 1: Identify correct method to convert column type
Theastype('category')method converts a Series to categorical type.Step 2: Check other options for errors
df['color'] = df.astype('category') tries to convert whole DataFrame, not column. df['color'] = pd.category(df['color']) uses non-existentpd.category(). df['color'] = df['color'].to_category() uses wrong method name.Final Answer:
df['color'] = df['color'].astype('category') -> Option BQuick Check:
astype('category') = Correct syntax [OK]
- Applying astype to whole DataFrame instead of column
- Using non-existent pd.category() function
- Using wrong method like to_category()
What will be the output of the following code?
import pandas as pd
df = pd.DataFrame({'fruit': ['apple', 'banana', 'apple', 'orange', 'banana']})
df['fruit'] = df['fruit'].astype('category')
print(df['fruit'].cat.categories)Solution
Step 1: Convert column to categorical and check categories
After conversion,cat.categoriesshows unique sorted categories.Step 2: Identify unique values in sorted order
Unique fruits are 'apple', 'banana', 'orange' in alphabetical order.Final Answer:
Index(['apple', 'banana', 'orange'], dtype='object') -> Option AQuick Check:
cat.categories = unique sorted values [OK]
- Expecting original list instead of unique categories
- Confusing categories with values
- Thinking cat attribute is missing
Identify the error in this code snippet that tries to convert a column to categorical:
import pandas as pd
df = pd.DataFrame({'size': ['S', 'M', 'L', 'M']})
df['size'] = df['size'].astype(category)Solution
Step 1: Check astype() argument
The argument toastype()must be a string 'category', not a bare word.Step 2: Verify other parts of code
DataFrame creation and column name are correct; astype() supports 'category'.Final Answer:
Missing quotes around 'category' in astype() -> Option CQuick Check:
Quotes needed for dtype string [OK]
- Forgetting quotes around 'category'
- Assuming astype() can't convert to category
- Mistaking column name errors
You have a DataFrame with a column 'city' containing 1 million rows but only 5 unique city names. Which approach optimizes memory and speeds up grouping by city?
Solution
Step 1: Understand memory and speed benefits of categorical
Converting to categorical stores unique values once, reducing memory and speeding grouping.Step 2: Evaluate other options
String type uses more memory; dropping duplicates loses data; grouping without conversion is slower.Final Answer:
Convert 'city' column to categorical type before grouping -> Option DQuick Check:
Categorical = Memory + speed optimization [OK]
- Using string type wastes memory
- Dropping duplicates loses data
- Grouping without conversion is slower
Ready to prove it?
Pass the test and this pattern moves unknown
