Using categorical data types helps save memory when working with repeated text values in data. It makes your data smaller and faster to use.
Memory savings with categoricals in Pandas
df['column'] = df['column'].astype('category')
import pandas as pd data = ['red', 'blue', 'red', 'green', 'blue'] df = pd.DataFrame({'color': data}) df['color'] = df['color'].astype('category')
df['color_codes'] = df['color'].cat.codes
This code shows how converting a text column to categorical reduces memory use and lists the unique categories.
import pandas as pd # Create a DataFrame with repeated text values colors = ['red', 'blue', 'red', 'green', 'blue', 'green', 'red', 'blue'] df = pd.DataFrame({'color': colors}) # Check memory usage before conversion mem_before = df.memory_usage(deep=True)['color'] # Convert to categorical type df['color'] = df['color'].astype('category') # Check memory usage after conversion mem_after = df.memory_usage(deep=True)['color'] print(f"Memory before: {mem_before} bytes") print(f"Memory after: {mem_after} bytes") # Show the DataFrame and categories print(df) print(f"Categories: {df['color'].cat.categories.tolist()}")
Categorical columns are best for columns with repeated values and few unique items.
Operations like sorting or grouping can be faster on categorical columns.
Be careful when mixing categorical and non-categorical data to avoid errors.
Categoricals save memory by storing repeated text values once.
Use astype('category') to convert columns.
Memory savings help with faster and efficient data analysis.
Practice
What is the main benefit of converting a pandas column to category type?
Solution
Step 1: Understand what
Thecategorytype doescategorytype stores repeated text values once and uses codes internally.Step 2: Identify the main benefit
This reduces memory usage because repeated strings are not stored multiple times.Final Answer:
It saves memory by storing repeated values efficiently -> Option BQuick Check:
Memory savings = A [OK]
- Thinking it sorts data automatically
- Confusing category with string conversion
- Assuming it removes missing values
Which of the following is the correct way to convert a pandas DataFrame column df['color'] to a categorical type?
import pandas as pd
df = pd.DataFrame({'color': ['red', 'blue', 'red', 'green']})Solution
Step 1: Recall pandas syntax for type conversion
Useastype('category')to convert a column to categorical type.Step 2: Check each option
Only df['color'] = df['color'].astype('category') uses the correctastypemethod with 'category' string.Final Answer:
df['color'] = df['color'].astype('category') -> Option AQuick Check:
astype('category') = A [OK]
- Using non-existent methods like to_category()
- Trying to call pd.category() which does not exist
- Using convert() instead of astype()
What will be the output of the following code?
import pandas as pd
import sys
df = pd.DataFrame({'fruit': ['apple', 'banana', 'apple', 'banana', 'cherry']})
mem_before = df['fruit'].memory_usage()
df['fruit'] = df['fruit'].astype('category')
mem_after = df['fruit'].memory_usage()
print(mem_before, mem_after)Solution
Step 1: Calculate memory before conversion
Strings take more memory; here memory_usage() returns 112 bytes before conversion.Step 2: Calculate memory after conversion to category
Category stores codes and unique values separately, reducing memory to 80 bytes.Final Answer:
112 80 -> Option AQuick Check:
Memory before > after = C [OK]
- Assuming memory stays the same
- Thinking memory increases after conversion
- Confusing order of printed values
Identify the error in the following code that tries to convert a column to categorical and save memory:
import pandas as pd
df = pd.DataFrame({'city': ['NY', 'LA', 'NY', 'SF']})
df['city'] = df['city'].astype(category)Solution
Step 1: Check astype argument
The argument toastypemust be a string 'category', but here category is unquoted, causing a NameError.Step 2: Verify other parts
DataFrame creation and column name are correct; astype supports 'category'.Final Answer:
Missing quotes around 'category' in astype -> Option CQuick Check:
Quotes needed for 'category' string [OK]
- Forgetting quotes around 'category'
- Thinking astype can't convert to category
- Assuming column name is wrong
You have a DataFrame with a column df['status'] containing 1 million rows with only 3 unique values: 'new', 'in_progress', 'done'. How can you reduce memory usage effectively?
Solution
Step 1: Understand the data characteristics
With only 3 unique values repeated 1 million times, storing as category saves memory by storing unique values once.Step 2: Compare options
Converting to string keeps large memory; dropping column loses data; manual integer replacement is error-prone and less efficient.Final Answer:
Convert df['status'] to category type -> Option DQuick Check:
Few unique values + large rows = category [OK]
- Using string type which uses more memory
- Dropping column losing important data
- Manual integer replacement without category benefits
Ready to prove it?
Pass the test and this pattern moves unknown
