Zero Labs
Industry News / AI

Part 14: Data Manipulation in Categorical Data Management

Source · Towards AI By Raj kumar

From the publisher’s feed, collected in the ZeroLabs newsroom.

How Category Encoding and Label Handling Influence Bias and Model StabilityMachine learning models do not understand text. They work with numbers. When your dataset contains categories like product types, customer segments, or geographic regions, you face a fundamental challenge: converting these text labels into a format algorithms can process. Get this wrong and your model learns spurious patterns, fails to generalize, or crashes on new data.Categorical data management is more than just converting strings to numbers. It’s about preserving information, preventing bias, and ensuring your encoding scheme does not introduce artifacts that mislead your model. A poorly chosen encoding can make unrelated categories appear similar or create false ordinal relationships where none exist. Your model accuracy suffers not because the algorithm is flawed but because the data representation is broken.In this article, we’ll explore categorical data handling in pandas: creating categorical types, accessing category codes, reordering categories, adding new categories, and removing unused ones. Each operation impacts memory efficiency, model performance, and analytical correctness. Understanding these techniques helps you prepare data that leads to stable, unbiased models.Understanding Categorical Data TypesPandas offers two ways to represent categorical data: as regular strings (object dtype) or as categorical dtype. The difference matters for both performance and functionality.String representation stores each value as a separate string object. If you have a column with 1 million rows and only 5 unique categories, you’re storing 1 million separate string objects. This wastes memory and slows operations.Categorical representation stores unique categories once and uses integer codes to reference them. Those same 1 million rows now store only 5 string objects plus 1 million small integers. Memory usage drops dramatically. Operations like groupby, merge, and filtering run faster.Beyond efficiency, categorical dtype enables operations impossible with strings. You can define custom orderings, add categories without data, and ensure consistency across datasets. These capabilities are essential for proper model preparation.1. Creating Categorical DataConverting columns to categorical is straightforward but the details matter. You can convert existing data or create categorical columns from scratch.Basic Categorical Conversionimport pandas as pdimport numpy as np# Create sample data with repeated categoriesdata = pd.DataFrame({ 'product': ['Laptop', 'Mouse', 'Keyboard', 'Mouse', 'Laptop', 'Monitor', 'Keyboard', 'Mouse', 'Laptop', 'Monitor'], 'size': ['Large', 'Small', 'Medium', 'Small', 'Large', 'Large', 'Medium', 'Small', 'Large', 'Large'], 'price': [1200, 25, 75, 25, 1200, 300, 75, 25, 1200, 300]})print("Original Data:")print(data)print(f"\nData types:\n{data.dtypes}")print(f"\nMemory usage:\n{data.memory_usage(deep=True)}")Output:Original Data: product size price0 Laptop Large 12001 Mouse Small 252 Keyboard Medium 753 Mouse Small 254 Laptop Large 12005 Monitor Large 3006 Keyboard Medium 757 Mouse Small 258 Laptop Large 12009 Monitor Large 300Data types:product objectsize objectprice int64dtype: objectMemory usage:Index 132product 730size 650price 80dtype: int64Converting to Categorical# Convert to categoricaldata_cat = data.copy()data_cat['product'] = pd.Categorical(data_cat['product'])data_cat['size'] = pd.Categorical(data_cat['size'])print("\nAfter Categorical Conversion:")print(data_cat)print(f"\nData types:\n{data_cat.dtypes}")print(f"\nMemory usage:\n{data_cat.memory_usage(deep=True)}")# Calculate memory savingsoriginal_memory = data.memory_usage(deep=True).sum()categorical_memory = data_cat.memory_usage(deep=True).sum()savings = (1 - categorical_memory / original_memory) * 100print(f"\nMemory Savings: {savings:.1f}%")Output:After Categorical Conversion: product size price0 Laptop Large 12001 Mouse Small 252 Keyboard Medium 753 Mouse Small 254 Laptop Large 12005 Monitor Large 3006 Keyboard Medium 757 Mouse Small 258 Laptop Large 12009 Monitor Large 300Data types:product categorysize categoryprice int64dtype: objectMemory usage:Index 132product 362size 342price 80dtype: int64Memory Savings: 42.1%Specifying Categories Upfront# Define categories explicitlyall_products = ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Tablet', 'Phone']product_cat = pd.Categorical( data['product'], categories=all_products, ordered=False)print("\nCategorical with Explicit Categories:")print(product_cat)print(f"\nAll categories: {product_cat.categories.tolist()}")print(f"Used categories: {product_cat.value_counts().index.tolist()}")print(f"Unused categories: {set(all_products) - set(data['product'].unique())}")Output:Categorical with Explicit Categories:['Laptop', 'Mouse', 'Keyboard', 'Mouse', 'Laptop', 'Monitor', 'Keyboard', 'Mouse', 'Laptop', 'Monitor']Categories (6, object): ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Tablet', 'Phone']All categories: ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Tablet', 'Phone']Used categories: ['Laptop', 'Mouse', 'Monitor', 'Keyboard']Unused categories: {'Phone', 'Tablet'}Ordered Categories# Create ordered categorical for sizesize_order = ['Small', 'Medium', 'Large']data_cat['size_ordered'] = pd.Categorical( data['size'], categories=size_order, ordered=True)print("\nOrdered Categorical (Size):")print(data_cat[['size_ordered']])print(f"\nIs ordered: {data_cat['size_ordered'].cat.ordered}")print(f"\nCategories: {data_cat['size_ordered'].cat.categories.tolist()}")# Comparison works with ordered categoriesprint("\nComparison operations:")print(data_cat['size_ordered'] >= 'Medium')Output:Ordered Categorical (Size): size_ordered0 Large1 Small2 Medium3 Small4 Large5 Large6 Medium7 Small8 Large9 LargeIs ordered: TrueCategories: ['Small', 'Medium', 'Large']Comparison operations:0 True1 False2 True3 False4 True5 True6 True7 False8 True9 TrueName: size_ordered, dtype: bool2. Getting Categorical CodesUnder the hood, categorical data uses integer codes to represent categories. Accessing these codes is essential for understanding how your data will be interpreted by models and for implementing custom encoding schemes.Basic Code Access# Create categorical datacategories = pd.DataFrame({ 'department': pd.Categorical(['Sales', 'Engineering', 'Marketing', 'Sales', 'Engineering', 'HR', 'Marketing', 'Sales', 'HR', 'Engineering']), 'performance': pd.Categorical(['Good', 'Excellent', 'Fair', 'Excellent', 'Good', 'Fair', 'Good', 'Fair', 'Excellent', 'Good'])})print("Categorical Data:")print(categories)print()# Get codesprint("Department Codes:")print(categories['department'].cat.codes)print()print("Performance Codes:")print(categories['performance'].cat.codes)print()# Show category to code mappingprint("Department Category Mapping:")dept_categories = categories['department'].cat.categoriesfor i, cat in enumerate(dept_categories): print(f" {cat}: {i}")Output:Categorical Data: department performance0 Sales Good1 Engineering Excellent2 Marketing Fair3 Sales Excellent4 Engineering Good5 HR Fair6 Marketing Good7 Sales Fair8 HR Excellent9 Engineering GoodDepartment Codes:0 31 02 23 34 05 16 27 38 19 0dtype: int8Performance Codes:0 11 02 23 04 15 26 17 28 09 1dtype: int8Department Category Mapping: Engineering: 0 HR: 1 Marketing: 2 Sales: 3Using Codes for Analysis# Create DataFrame with codescategories_with_codes = categories.copy()categories_with_codes['dept_code'] = categories['department'].cat.codescategories_with_codes['perf_code'] = categories['performance'].cat.codesprint("\nData with Codes:")print(categories_with_codes)print()# Group by codesprint("Average Performance Code by Department:")avg_perf = categories_with_codes.groupby('department')['perf_code'].mean().round(2)print(avg_perf)print()# Map codes back to categoriesprint("Code to Category Lookup:")dept_lookup = dict(enumerate(categories['department'].cat.categories))print(f"Department codes: {dept_lookup}")Output:Data with Codes: department performance dept_code perf_code0 Sales Good 3 11 Engineering Excellent 0 02 Marketing Fair 2 23 Sales Excellent 3 04 Engineering Good 0 15 HR Fair 1 26 Marketing Good 2 17 Sales Fair 3 28 HR Excellent 1 09 Engineering Good 0 1Average Performance Code by Department:departmentEngineering 0.67HR 1.00Marketing 1.50Sales 1.00Name: perf_code, dtype: float64Code to Category Lookup:Department codes: {0: 'Engineering', 1: 'HR', 2: 'Marketing', 3: 'Sales'}Codes vs Values# Demonstrate difference between codes and valuessample_cat = pd.Categorical(['B', 'A', 'C', 'A', 'B'], categories=['A', 'B', 'C'], ordered=True)print("Categorical Values:")print(sample_cat)print()print("Codes (based on category order):")print(sample_cat.codes)print()print("Category order determines codes:")for i, cat in enumerate(sample_cat.categories): print(f" '{cat}' -> code {i}")Output:Categorical Values:['B', 'A', 'C', 'A', 'B']Categories (3, object): ['A' Codes (based on category order):[1 0 2 0 1]Category order determines codes: 'A' -> code 0 'B' -> code 1 'C' -> code 23. Reordering CategoriesThe order of categories matters for ordered categoricals and affects how codes are assigned. Reordering changes the mapping between categories and their numeric representations.Basic Reordering# Create ordered categorical with initial orderratings = pd.Categorical( ['Good', 'Poor', 'Excellent', 'Fair', 'Good', 'Poor', 'Excellent'], categories=['Poor', 'Fair', 'Good', 'Excellent'], ordered=True)print("Original Order:")print(ratings)print(f"Categories: {ratings.categories.tolist()}")print(f"Codes: {ratings.codes}")print()# Reorder categoriesratings_reordered = ratings.reorder_categories(['Excellent', 'Good', 'Fair', 'Poor'])print("After Reordering:")print(ratings_reordered)print(f"Categories: {ratings_reordered.categories.tolist()}")print(f"Codes: {ratings_reordered.codes}")Output:Original Order:['Good', 'Poor', 'Excellent', 'Fair', 'Good', 'Poor', 'Excellent']Categories (4, object): ['Poor' Codes: [2 0 3 1 2 0 3]After Reordering:['Good', 'Poor', 'Excellent', 'Fair', 'Good', 'Poor', 'Excellent']Categories (4, object): ['Excellent' Codes: [1 3 0 2 1 3 0]Practical Example: Priority Levels# Create task priority datatasks = pd.DataFrame({ 'task': ['Task A', 'Task B', 'Task C', 'Task D', 'Task E'], 'priority': ['Medium', 'High', 'Low', 'High', 'Medium']})# Initial categorical (alphabetical)tasks['priority_cat'] = pd.Categorical(tasks['priority'], ordered=True)print("Initial Priority (Alphabetical Order):")print(tasks)print(f"Categories: {tasks['priority_cat'].cat.categories.tolist()}")print(f"Codes: {tasks['priority_cat'].cat.codes.tolist()}")print()# Reorder to logical priority ordertasks['priority_cat'] = tasks['priority_cat'].cat.reorder_categories( ['Low', 'Medium', 'High'], ordered=True)print("After Reordering (Logical Priority):")print(tasks)print(f"Categories: {tasks['priority_cat'].cat.categories.tolist()}")print(f"Codes: {tasks['priority_cat'].cat.codes.tolist()}")print()# Now comparisons work logicallyprint("High Priority Tasks (Priority >= 'Medium'):")high_priority = tasks[tasks['priority_cat'] >= 'Medium']print(high_priority)Output:Initial Priority (Alphabetical Order): task priority priority_cat0 Task A Medium Medium1 Task B High High2 Task C Low Low3 Task D High High4 Task E Medium MediumCategories: ['High', 'Low', 'Medium']Codes: [2, 0, 1, 0, 2]After Reordering (Logical Priority): task priority priority_cat0 Task A Medium Medium1 Task B High High2 Task C Low Low3 Task D High High4 Task E Medium MediumCategories: ['Low', 'Medium', 'High']Codes: [1, 2, 0, 2, 1]High Priority Tasks (Priority >= 'Medium'): task priority priority_cat0 Task A Medium Medium1 Task B High High3 Task D High High4 Task E Medium MediumReordering for Analysis# Create survey response dataresponses = pd.DataFrame({ 'question': ['Q1', 'Q1', 'Q1', 'Q2', 'Q2', 'Q2'], 'response': ['Agree', 'Disagree', 'Strongly Agree', 'Neutral', 'Agree', 'Strongly Disagree']})# Convert to ordered categorical with proper orderresponse_order = ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree']responses['response_cat'] = pd.Categorical( responses['response'], categories=response_order, ordered=True)print("Survey Responses:")print(responses)print()# Calculate numeric scores based on orderresponses['score'] = responses['response_cat'].cat.codesprint("With Numeric Scores:")print(responses)print()# Calculate average by questionprint("Average Score by Question:")avg_scores = responses.groupby('question')['score'].mean()print(avg_scores)Output:Survey Responses: question response response_cat0 Q1 Agree Agree1 Q1 Disagree Disagree2 Q1 Strongly Agree Strongly Agree3 Q2 Neutral Neutral4 Q2 Agree Agree5 Q2 Strongly Disagree Strongly DisagreeWith Numeric Scores: question response response_cat score0 Q1 Agree Agree 31 Q1 Disagree Disagree 12 Q1 Strongly Agree Strongly Agree 43 Q2 Neutral Neutral 24 Q2 Agree Agree 35 Q2 Strongly Disagree Strongly Disagree 0Average Score by Question:questionQ1 2.666667Q2 1.666667Name: score, dtype: float644. Adding New CategoriesWhen working with categorical data, you may need to add categories that don’t exist in your current dataset. This is essential for ensuring consistency across datasets or preparing for future values.Adding Categories Without Data# Create initial categoricalproducts = pd.Categorical(['Laptop', 'Mouse', 'Keyboard', 'Laptop'])print("Initial Categories:")print(f"Categories: {products.categories.tolist()}")print(f"Values: {products.tolist()}")print()# Add new categoryproducts_extended = products.add_categories('Monitor')print("After Adding 'Monitor':")print(f"Categories: {products_extended.categories.tolist()}")print(f"Values: {products_extended.tolist()}")print()# Add multiple categoriesproducts_extended = products.add_categories(['Tablet', 'Phone'])print("After Adding Multiple Categories:")print(f"Categories: {products_extended.categories.tolist()}")Output:Initial Categories:Categories: ['Keyboard', 'Laptop', 'Mouse']Values: ['Laptop', 'Mouse', 'Keyboard', 'Laptop']After Adding 'Monitor':Categories: ['Keyboard', 'Laptop', 'Mouse', 'Monitor']Values: ['Laptop', 'Mouse', 'Keyboard', 'Laptop']After Adding Multiple Categories:Categories: ['Keyboard', 'Laptop', 'Mouse', 'Tablet', 'Phone']Using Added Categories# Create DataFrame with categorical columndf = pd.DataFrame({ 'product': pd.Categorical(['Laptop', 'Mouse', 'Keyboard'])})print("Original Data:")print(df)print(f"Categories: {df['product'].cat.categories.tolist()}")print()# Add new categorydf['product'] = df['product'].cat.add_categories('Monitor')print("After Adding 'Monitor' Category:")print(f"Categories: {df['product'].cat.categories.tolist()}")print()# Now we can use the new categorydf.loc[3] = 'Monitor'print("After Adding Monitor Value:")print(df)Output:Original Data: product0 Laptop1 Mouse2 KeyboardCategories: ['Keyboard', 'Laptop', 'Mouse']After Adding 'Monitor' Category:Categories: ['Keyboard', 'Laptop', 'Mouse', 'Monitor']After Adding Monitor Value: product0 Laptop1 Mouse2 Keyboard3 MonitorPreventing Errors with Pre-defined Categories# Example: Preparing for merge operationssales_q1 = pd.DataFrame({ 'product': pd.Categorical(['Laptop', 'Mouse']), 'sales': [10, 50]})sales_q2 = pd.DataFrame({ 'product': pd.Categorical(['Keyboard', 'Monitor']), 'sales': [30, 20]})print("Q1 Sales:")print(sales_q1)print(f"Categories: {sales_q1['product'].cat.categories.tolist()}")print()print("Q2 Sales:")print(sales_q2)print(f"Categories: {sales_q2['product'].cat.categories.tolist()}")print()# Define all possible productsall_products = ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Tablet']# Ensure both have same categoriessales_q1['product'] = sales_q1['product'].cat.add_categories( [p for p in all_products if p not in sales_q1['product'].cat.categories])sales_q2['product'] = sales_q2['product'].cat.add_categories( [p for p in all_products if p not in sales_q2['product'].cat.categories])print("After Standardizing Categories:")print(f"Q1 Categories: {sales_q1['product'].cat.categories.tolist()}")print(f"Q2 Categories: {sales_q2['product'].cat.categories.tolist()}")print()# Now can safely concatenatecombined = pd.concat([sales_q1, sales_q2], ignore_index=True)print("Combined Sales:")print(combined)Output:Q1 Sales: product sales0 Laptop 101 Mouse 50Categories: ['Laptop', 'Mouse']Q2 Sales: product sales0 Keyboard 301 Monitor 20Categories: ['Keyboard', 'Monitor']After Standardizing Categories:Q1 Categories: ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Tablet']Q2 Categories: ['Keyboard', 'Monitor', 'Laptop', 'Mouse', 'Tablet']Combined Sales: product sales0 Laptop 101 Mouse 502 Keyboard 303 Monitor 205. Removing Unused CategoriesOver time, categorical columns may accumulate unused categories from operations like filtering or merging. These unused categories can cause issues with analysis and modeling. Removing them keeps your data clean and prevents confusion.Identifying and Removing Unused Categories# Create data with unused categoriesall_sizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL']inventory = pd.DataFrame({ 'item': ['Shirt A', 'Shirt B', 'Shirt C', 'Shirt D'], 'size': pd.Categorical(['M', 'L', 'M', 'L'], categories=all_sizes)})print("Inventory Data:")print(inventory)print(f"\nAll Categories: {inventory['size'].cat.categories.tolist()}")print(f"Used Categories: {inventory['size'].unique().tolist()}")print(f"Value Counts:\n{inventory['size'].value_counts()}")print()# Remove unused categoriesinventory['size_clean'] = inventory['size'].cat.remove_unused_categories()print("After Removing Unused Categories:")print(f"All Categories: {inventory['size_clean'].cat.categories.tolist()}")print(f"Value Counts:\n{inventory['size_clean'].value_counts()}")Output:Inventory Data: item size0 Shirt A M1 Shirt B L2 Shirt C M3 Shirt D LAll Categories: ['XS', 'S', 'M', 'L', 'XL', 'XXL']Used Categories: ['M', 'L']Value Counts:M 2L 2S 0XS 0XL 0XXL 0Name: size, dtype: int64After Removing Unused Categories:All Categories: ['M', 'L']Value Counts:M 2L 2Name: size, dtype: int64Practical Example: After Filtering# Create full product catalogcatalog = pd.DataFrame({ 'product': pd.Categorical(['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Tablet', 'Phone', 'Headphones', 'Webcam']), 'price': [1200, 25, 75, 300, 500, 800, 150, 80], 'in_stock': [True, True, True, True, False, False, True, False]})print("Full Catalog:")print(catalog)print(f"Product Categories: {catalog['product'].cat.categories.tolist()}")print()# Filter to in-stock itemsin_stock = catalog[catalog['in_stock']].copy()print("In-Stock Items (Before Cleanup):")print(in_stock)print(f"Product Categories: {in_stock['product'].cat.categories.tolist()}")print()# Remove unused categoriesin_stock['product'] = in_stock['product'].cat.remove_unused_categories()print("In-Stock Items (After Cleanup):")print(in_stock)print(f"Product Categories: {in_stock['product'].cat.categories.tolist()}")Output:Full Catalog: product price in_stock0 Laptop 1200 True1 Mouse 25 True2 Keyboard 75 True3 Monitor 300 True4 Tablet 500 False5 Phone 800 False6 Headphones 150 True7 Webcam 80 FalseProduct Categories: ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Tablet', 'Phone', 'Headphones', 'Webcam']In-Stock Items (Before Cleanup): product price in_stock0 Laptop 1200 True1 Mouse 25 True2 Keyboard 75 True3 Monitor 300 True6 Headphones 150 TrueProduct Categories: ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Tablet', 'Phone', 'Headphones', 'Webcam']In-Stock Items (After Cleanup): product price in_stock0 Laptop 1200 True1 Mouse 25 True2 Keyboard 75 True3 Monitor 300 True6 Headphones 150 TrueProduct Categories: ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones']Why Removing Unused Categories Matters# Demonstrate impact on operations# Create data with unused categoriesdata = pd.DataFrame({ 'category': pd.Categorical(['A', 'B', 'A', 'B'], categories=['A', 'B', 'C', 'D', 'E'])})print("Data with Unused Categories:")print(data)print()print("Value Counts (includes unused):")print(data['category'].value_counts())print()# After removing unuseddata['category_clean'] = data['category'].cat.remove_unused_categories()print("Value Counts (after cleanup):")print(data['category_clean'].value_counts())print()# Impact on dummy variablesprint("Dummy Variables (before cleanup):")dummies_before = pd.get_dummies(data['category'], prefix='cat')print(dummies_before)print(f"Shape: {dummies_before.shape}")print()print("Dummy Variables (after cleanup):")dummies_after = pd.get_dummies(data['category_clean'], prefix='cat')print(dummies_after)print(f"Shape: {dummies_after.shape}")Output:Data with Unused Categories: category0 A1 B2 A3 BValue Counts (includes unused):A 2B 2C 0D 0E 0Name: category, dtype: int64Value Counts (after cleanup):A 2B 2Name: category_clean, dtype: int64Dummy Variables (before cleanup): cat_A cat_B cat_C cat_D cat_E0 1 0 0 0 01 0 1 0 0 02 1 0 0 0 03 0 1 0 0 0Shape: (4, 5)Dummy Variables (after cleanup): cat_A cat_B0 1 01 0 12 1 03 0 1Shape: (4, 2)Complete End-to-End Example: Customer Segmentation PipelineHere’s a comprehensive program demonstrating all categorical operations in a realistic customer analysis scenario.import pandas as pdimport numpy as npprint("="*70)print("CUSTOMER SEGMENTATION - CATEGORICAL DATA MANAGEMENT")print("="*70)# STEP 1: Create customer data with categorical variablesprint("\n" + "="*70)print("STEP 1: LOAD CUSTOMER DATA")print("="*70)np.random.seed(42)# Generate sample customer datacustomer_data = pd.DataFrame({ 'customer_id': range(1, 21), 'segment': np.random.choice(['Bronze', 'Silver', 'Gold', 'Platinum'], 20), 'region': np.random.choice(['North', 'South', 'East', 'West'], 20), 'product_interest': np.random.choice(['Electronics', 'Clothing', 'Home'], 20), 'satisfaction': np.random.choice(['Very Satisfied', 'Satisfied', 'Neutral', 'Dissatisfied'], 20), 'purchase_amount': np.random.randint(100, 1000, 20)})print("\nOriginal Customer Data (first 10):")print(customer_data.head(10))print(f"\nData Types:\n{customer_data.dtypes}")print(f"\nMemory Usage: {customer_data.memory_usage(deep=True).sum()} bytes")# STEP 2: Convert to categoricalprint("\n" + "="*70)print("STEP 2: CONVERT TO CATEGORICAL")print("="*70)# Define all possible categoriesall_segments = ['Bronze', 'Silver', 'Gold', 'Platinum', 'Diamond']all_regions = ['North', 'South', 'East', 'West']all_products = ['Electronics', 'Clothing', 'Home', 'Sports', 'Books']satisfaction_levels = ['Very Dissatisfied', 'Dissatisfied', 'Neutral', 'Satisfied', 'Very Satisfied']# Convert with explicit categoriescustomer_data['segment_cat'] = pd.Categorical( customer_data['segment'], categories=all_segments, ordered=True)customer_data['region_cat'] = pd.Categorical( customer_data['region'], categories=all_regions, ordered=False)customer_data['product_cat'] = pd.Categorical( customer_data['product_interest'], categories=all_products, ordered=False)customer_data['satisfaction_cat'] = pd.Categorical( customer_data['satisfaction'], categories=satisfaction_levels, ordered=True)print("\nAfter Categorical Conversion:")print(customer_data.dtypes)print(f"\nMemory Usage: {customer_data.memory_usage(deep=True).sum()} bytes")memory_saved = (1 - customer_data.memory_usage(deep=True).sum() / customer_data.astype(str).memory_usage(deep=True).sum()) * 100print(f"Memory Savings: {memory_saved:.1f}%")# STEP 3: Access categorical codesprint("\n" + "="*70)print("STEP 3: EXAMINE CATEGORICAL CODES")print("="*70)print("\nSegment Codes:")segment_codes = customer_data[['segment_cat']].copy()segment_codes['code'] = customer_data['segment_cat'].cat.codesprint(segment_codes.head(10))print("\nSegment Code Mapping:")for i, seg in enumerate(customer_data['segment_cat'].cat.categories): count = (customer_data['segment_cat'].cat.codes == i).sum() print(f" {seg} -> {i} (count: {count})")# STEP 4: Reorder satisfaction for logical orderingprint("\n" + "="*70)print("STEP 4: REORDER CATEGORIES")print("="*70)print("Satisfaction Before Reorder:")print(f"Categories: {customer_data['satisfaction_cat'].cat.categories.tolist()}")print(f"Sample codes: {customer_data['satisfaction_cat'].cat.codes[:5].tolist()}")# Already in correct order, but demonstrate the conceptprint("\nSatisfaction Order (Low to High):")for i, level in enumerate(satisfaction_levels): print(f" {i}: {level}")# Create numeric scores based on satisfactioncustomer_data['satisfaction_score'] = customer_data['satisfaction_cat'].cat.codesprint("\nCustomer Data with Satisfaction Scores:")print(customer_data[['customer_id', 'satisfaction_cat', 'satisfaction_score']].head(10))# STEP 5: Identify and analyze category usageprint("\n" + "="*70)print("STEP 5: ANALYZE CATEGORY USAGE")print("="*70)print("Segment Distribution:")print(customer_data['segment_cat'].value_counts())print(f"\nUnused segments: {set(all_segments) - set(customer_data['segment'].unique())}")print("\nProduct Interest Distribution:")print(customer_data['product_cat'].value_counts())print(f"\nUnused products: {set(all_products) - set(customer_data['product_interest'].unique())}")# STEP 6: Filter data and remove unused categoriesprint("\n" + "="*70)print("STEP 6: FILTER AND CLEANUP")print("="*70)# Filter to high-value customers (Satisfied+)high_satisfaction = customer_data[ customer_data['satisfaction_cat'] >= 'Satisfied'].copy()print(f"\nHigh Satisfaction Customers: {len(high_satisfaction)}")print("\nSatisfaction Categories (before cleanup):")print(high_satisfaction['satisfaction_cat'].cat.categories.tolist())print("\nValue Counts:")print(high_satisfaction['satisfaction_cat'].value_counts())# Remove unused categorieshigh_satisfaction['satisfaction_cat'] = ( high_satisfaction['satisfaction_cat'].cat.remove_unused_categories())print("\nSatisfaction Categories (after cleanup):")print(high_satisfaction['satisfaction_cat'].cat.categories.tolist())# STEP 7: Add new category for future useprint("\n" + "="*70)print("STEP 7: ADD NEW CATEGORIES")print("="*70)print("Current Segments:")print(customer_data['segment_cat'].cat.categories.tolist())# Check if Diamond is already in categoriesif 'Diamond' not in customer_data['segment_cat'].cat.categories: customer_data['segment_cat'] = customer_data['segment_cat'].cat.add_categories(['Diamond'])print("\nAfter Adding 'Diamond' Tier:")print(customer_data['segment_cat'].cat.categories.tolist())# Simulate upgradecustomer_data.loc[customer_data['purchase_amount'] > 900, 'segment_cat'] = 'Diamond'print("\nSegment Distribution After Upgrades:")print(customer_data['segment_cat'].value_counts())# STEP 8: Create dummy variables for modelingprint("\n" + "="*70)print("STEP 8: CREATE DUMMY VARIABLES")print("="*70)# Before cleanup - includes all categoriesdummies_all = pd.get_dummies(customer_data['segment_cat'], prefix='segment')print(f"Dummy variables (all categories): {dummies_all.shape}")print(dummies_all.head())# After removing unusedcustomer_data['segment_clean'] = ( customer_data['segment_cat'].cat.remove_unused_categories())dummies_clean = pd.get_dummies(customer_data['segment_clean'], prefix='segment')print(f"\nDummy variables (used categories): {dummies_clean.shape}")print(dummies_clean.head())# STEP 9: Aggregate analysis by categoriesprint("\n" + "="*70)print("STEP 9: AGGREGATE ANALYSIS")print("="*70)print("Average Purchase Amount by Segment:")segment_stats = customer_data.groupby('segment_cat')['purchase_amount'].agg([ ('count', 'count'), ('mean', 'mean'), ('total', 'sum')]).round(2)print(segment_stats)print("\nAverage Satisfaction Score by Region:")region_satisfaction = customer_data.groupby('region_cat')['satisfaction_score'].mean().round(2)print(region_satisfaction)print("\nCustomer Count by Product Interest and Segment:")cross_tab = pd.crosstab( customer_data['product_cat'], customer_data['segment_cat'], margins=True)print(cross_tab)# STEP 10: Model preparation summaryprint("\n" + "="*70)print("STEP 10: MODEL PREPARATION SUMMARY")print("="*70)# Create feature matrixfeatures = customer_data[['segment_clean', 'region_cat', 'product_cat', 'satisfaction_score', 'purchase_amount']].copy()# Get dummies for all categorical variablesfeatures_encoded = pd.get_dummies( features, columns=['segment_clean', 'region_cat', 'product_cat'], drop_first=True)print("Encoded Feature Matrix:")print(features_encoded.head())print(f"\nShape: {features_encoded.shape}")print(f"\nFeature Names: {features_encoded.columns.tolist()}")print("\nData Ready for Modeling:")print(f" Total Customers: {len(features_encoded)}")print(f" Total Features: {features_encoded.shape[1]}")print(f" Categorical Variables Encoded: 3")print(f" Numerical Features: 2")print("\n" + "="*70)print("ANALYSIS COMPLETE")print("="*70)Complete Output:======================================================================CUSTOMER SEGMENTATION - CATEGORICAL DATA MANAGEMENT============================================================================================================================================STEP 1: LOAD CUSTOMER DATA======================================================================Original Customer Data (first 10): customer_id segment region product_interest satisfaction purchase_amount0 1 Silver North Electronics Very Satisfied 4741 2 Gold East Clothing Very Satisfied 8322 3 Silver South Clothing Neutral 2113 4 Platinum South Home Dissatisfied 8584 5 Bronze East Electronics Satisfied 5625 6 Silver North Home Very Satisfied 7486 7 Gold South Clothing Neutral 3667 8 Silver North Electronics Very Satisfied 8328 9 Platinum West Clothing Satisfied 2529 10 Bronze North Home Neutral 861Data Types:customer_id int64segment objectregion objectproduct_interest objectsatisfaction objectpurchase_amount int64dtype: objectMemory Usage: 3652 bytes======================================================================STEP 2: CONVERT TO CATEGORICAL======================================================================After Categorical Conversion:customer_id int64segment objectregion objectproduct_interest objectsatisfaction objectpurchase_amount int64segment_cat categoryregion_cat categoryproduct_cat categorysatisfaction_cat categorydtype: objectMemory Usage: 4548 bytesMemory Savings: 37.4%======================================================================STEP 3: EXAMINE CATEGORICAL CODES======================================================================Segment Codes: segment_cat code0 Silver 11 Gold 22 Silver 13 Platinum 34 Bronze 05 Silver 16 Gold 27 Silver 18 Platinum 39 Bronze 0Segment Code Mapping: Bronze -> 0 (count: 6) Silver -> 1 (count: 6) Gold -> 2 (count: 3) Platinum -> 3 (count: 5) Diamond -> 4 (count: 0)======================================================================STEP 4: REORDER CATEGORIES======================================================================Satisfaction Before Reorder:Categories: ['Very Dissatisfied', 'Dissatisfied', 'Neutral', 'Satisfied', 'Very Satisfied']Sample codes: [4, 4, 2, 1, 3]Satisfaction Order (Low to High): 0: Very Dissatisfied 1: Dissatisfied 2: Neutral 3: Satisfied 4: Very SatisfiedCustomer Data with Satisfaction Scores: customer_id satisfaction_cat satisfaction_score0 1 Very Satisfied 41 2 Very Satisfied 42 3 Neutral 23 4 Dissatisfied 14 5 Satisfied 35 6 Very Satisfied 46 7 Neutral 27 8 Very Satisfied 48 9 Satisfied 39 10 Neutral 2======================================================================STEP 5: ANALYZE CATEGORY USAGE======================================================================Segment Distribution:Silver 6Bronze 6Platinum 5Gold 3Diamond 0Name: segment_cat, dtype: int64Unused segments: {'Diamond'}Product Interest Distribution:Clothing 8Electronics 7Home 5Sports 0Books 0Name: product_cat, dtype: int64Unused products: {'Sports', 'Books'}======================================================================STEP 6: FILTER AND CLEANUP======================================================================High Satisfaction Customers: 12Satisfaction Categories (before cleanup):['Very Dissatisfied', 'Dissatisfied', 'Neutral', 'Satisfied', 'Very Satisfied']Value Counts:Very Satisfied 7Satisfied 5Dissatisfied 0Neutral 0Very Dissatisfied 0Name: satisfaction_cat, dtype: int64Satisfaction Categories (after cleanup):['Satisfied', 'Very Satisfied']======================================================================STEP 7: ADD NEW CATEGORIES======================================================================Current Segments:['Bronze', 'Silver', 'Gold', 'Platinum', 'Diamond']After Adding 'Diamond' Tier:['Bronze', 'Silver', 'Gold', 'Platinum', 'Diamond']Segment Distribution After Upgrades:Silver 6Bronze 6Platinum 4Gold 3Diamond 1Name: segment_cat, dtype: int64======================================================================STEP 8: CREATE DUMMY VARIABLES======================================================================Dummy variables (all categories): (20, 5) segment_Bronze segment_Silver segment_Gold segment_Platinum segment_Diamond0 0 1 0 0 01 0 0 1 0 02 0 1 0 0 03 0 0 0 1 04 1 0 0 0 0Dummy variables (used categories): (20, 5) segment_Bronze segment_Silver segment_Gold segment_Platinum segment_Diamond0 0 1 0 0 01 0 0 1 0 02 0 1 0 0 03 0 0 0 1 04 1 0 0 0 0======================================================================STEP 9: AGGREGATE ANALYSIS======================================================================Average Purchase Amount by Segment: count mean totalsegment_cat Bronze 6.0 510.83 3065.0Silver 6.0 503.50 3021.0Gold 3.0 489.67 1469.0Platinum 4.0 551.50 2206.0Diamond 1.0 944.00 944.0Average Satisfaction Score by Region:region_catNorth 2.86South 2.00East 3.17West 2.50Name: satisfaction_score, dtype: float64Customer Count by Product Interest and Segment:segment_cat Bronze Gold Platinum Silver Diamond Allproduct_cat Clothing 3 1 2 2 0 8Electronics 2 2 1 2 0 7Home 1 0 1 2 1 5All 6 3 4 6 1 20======================================================================STEP 10: MODEL PREPARATION SUMMARY======================================================================Encoded Feature Matrix: satisfaction_score purchase_amount segment_clean_Silver segment_clean_Gold segment_clean_Platinum segment_clean_Diamond region_cat_South region_cat_East region_cat_West product_cat_Electronics product_cat_Home0 4 474 1 0 0 0 0 0 0 1 01 4 832 0 1 0 0 0 1 0 0 02 2 211 1 0 0 0 1 0 0 0 03 1 858 0 0 1 0 1 0 0 0 14 3 562 0 0 0 0 0 1 0 1 0Shape: (20, 11)Feature Names: ['satisfaction_score', 'purchase_amount', 'segment_clean_Silver', 'segment_clean_Gold', 'segment_clean_Platinum', 'segment_clean_Diamond', 'region_cat_South', 'region_cat_East', 'region_cat_West', 'product_cat_Electronics', 'product_cat_Home']Data Ready for Modeling: Total Customers: 20 Total Features: 11 Categorical Variables Encoded: 3 Numerical Features: 2======================================================================ANALYSIS COMPLETE======================================================================How Category Encoding Influences Model BehaviorThe way you encode categorical variables directly impacts what patterns your model can learn and how well it generalizes.Label Encoding Creates False OrderingsSimply converting categories to integers (Bronze=0, Silver=1, Gold=2, Platinum=3) implies an arithmetic relationship. The model learns that Platinum is “three times” Bronze, which may not reflect reality. For truly nominal categories like product types or regions, this false ordering introduces bias.One-Hot Encoding Prevents BiasCreating binary columns for each category (dummy variables) treats categories as independent. No false arithmetic relationships exist. This is appropriate for nominal variables but increases dimensionality.Ordered Categories Enable ComparisonFor truly ordered categories like satisfaction levels or priority tiers, maintaining order lets you use comparison operators and enables ordinal encoding where the numeric codes reflect actual ranking.Unused Categories Waste ResourcesCategories defined but never present in your data create unnecessary dummy variables, increase memory usage, and may confuse models. Removing them keeps your feature space clean.Inconsistent Categories Break PipelinesIf training data has categories that test data lacks or vice versa, your encoding scheme fails. Pre-defining all possible categories and handling them consistently prevents production errors.Best Practices for Categorical Data ManagementConvert to categorical early. As soon as you identify categorical columns, convert them. The memory savings and functionality benefits compound throughout analysis.Define all categories upfront. Especially for nominal variables with known values, specify categories explicitly rather than inferring from data. This prevents inconsistencies across datasets.Use ordered=True only when order matters. Don’t make categories ordered just because they convert to numbers nicely. Order should reflect real-world relationships.Remove unused categories before modeling. After filtering or transforming data, clean up unused categories to prevent creating unnecessary features.Document category mappings. Save the mapping between categories and codes. You’ll need it for interpreting model coefficients and handling new data.Standardize categories across datasets. When combining data from multiple sources, ensure categorical columns have identical category sets and orderings.Validate category consistency. Before merging or concatenating DataFrames with categorical columns, verify that categories match or explicitly handle differences.Common Pitfalls to AvoidForgetting to specify categories when concatenating. Concatenating DataFrames with different categorical levels creates inconsistent results. Standardize categories first.Using string operations on categorical columns. Many string methods don’t work on categorical dtype. Convert to string for manipulation, then back to categorical if needed.Assuming alphabetical order is logical order. Categories default to alphabetical order unless you specify otherwise. This rarely matches real-world ordering for things like sizes or ratings.Not removing unused categories after filtering. Filtered DataFrames retain the original categorical levels, which can confuse analysis and create extra dummy variables.Mixing ordered and unordered categoricals. Be consistent. If satisfaction is ordered in one dataset, make it ordered everywhere. Inconsistency causes comparison errors.Final ThoughtsCategorical data management is foundational to building stable, unbiased models. The operations we’ve covered — creating categoricals, accessing codes, reordering, adding categories, and removing unused ones — directly influence model behavior and performance.Every encoding choice carries consequences. Label encoding introduces arithmetic relationships that may not exist. One-hot encoding prevents bias but increases dimensionality. Ordered categories enable meaningful comparisons but require thoughtful ordering. Unused categories waste resources and may cause errors. Inconsistent categories break production pipelines.The key is thinking through your data’s meaning before choosing encoding strategies. Are categories truly ordered or just nominal? Do you know all possible values or might new ones appear? Will you combine data from multiple sources? These questions guide your categorical data management approach.Proper categorical handling improves model stability by preventing spurious patterns from encoding artifacts. It reduces bias by not imposing false relationships between categories. It prevents errors by ensuring consistency across datasets. And it optimizes performance by reducing unnecessary features and memory usage.Whether you’re building classification models, running regression analysis, or preparing data for visualization, categorical data management is essential. Master these techniques and you build a foundation for accurate, stable, interpretable models.This guide is part of my ongoing series, “Data Manipulation in the Real World” where I focus on solving actual data engineering hurdles rather than toy examples. My goal is to give you practical Pandas skills that you can apply immediately to your professional projects.Found this guide valuable? Your engagement helps other developers discover these techniques. If this article helped you understand window functions better, please follow my page, give it a clap, leave a comment with your questions or use cases, and share it with your network. I respond to every technical question.Your engagement helps these guides reach practitioners who need them. What categorical encoding challenges have you faced? What strategies work best in your domain? Share your experiences in the comments below.Part 14: Data Manipulation in Categorical Data Management was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.