Part 11: Data Manipulation in Advanced Indexing
From the publisher’s feed, collected in the ZeroLabs newsroom.
How Index Strategy Impacts Performance, Traceability, and CorrectnessWorking with pandas DataFrames without understanding indexing is like navigating a city without street addresses. You might eventually find what you need, but you’ll waste time and probably get lost along the way. Advanced indexing techniques transform how you access, manipulate, and analyze data. The right index strategy can make your code faster, more maintainable, and less prone to errors.Indexes are more than just row labels. They’re organizational structures that determine how you query data, how operations align, and how efficiently your code runs. A well-designed index strategy can reduce query time from seconds to milliseconds. It can prevent subtle bugs caused by misaligned data. It can make complex hierarchical data intuitive to work with.In this article, we’ll explore multi-level indexing, selecting from multi-indexes, cross-sections, swapping levels, and sorting indexes. Each technique comes with practical examples and complete working output you can reference immediately.Understanding Index FundamentalsBefore diving into advanced techniques, let’s clarify what an index does. In pandas, an index provides labels for rows (and columns). The index serves three critical purposes:Data Alignment — Operations between DataFrames automatically align on index valuesFast Lookups — Hash-based indexing provides O(1) access to rowsData Organization — Hierarchical indexes represent complex relationshipsA simple index contains unique values. A multi-level index (also called hierarchical index) contains multiple levels of labels, allowing you to represent higher-dimensional data in a two-dimensional structure.1. Multi-Level Indexing: Building HierarchiesMulti-level indexing allows you to work with higher-dimensional data in a DataFrame. Instead of a single index value per row, you have multiple index values that form a hierarchy. This is essential for representing data with natural groupings like geographical hierarchies, time series with multiple frequencies, or nested categories.When to Use Multi-Level IndexingTime series data with multiple frequencies (year, quarter, month)Geographic data with hierarchies (country, state, city)Product data with categories (department, category, subcategory)Panel data with multiple dimensions (entity, time period)Any data with natural hierarchical groupingsCreating Multi-Level Indexesimport pandas as pdimport numpy as np# Method 1: Using set_index with multiple columnssales_data = pd.DataFrame({ 'region': ['North', 'North', 'North', 'South', 'South', 'South'], 'quarter': ['Q1', 'Q2', 'Q3', 'Q1', 'Q2', 'Q3'], 'revenue': [100000, 120000, 115000, 95000, 105000, 110000], 'units_sold': [1200, 1400, 1350, 1100, 1250, 1300]})print("Original DataFrame:")print(sales_data)print()# Create multi-level indexsales_indexed = sales_data.set_index(['region', 'quarter'])print("With Multi-Level Index:")print(sales_indexed)print()# Method 2: Using MultiIndex.from_tuplesindex_tuples = [ ('Electronics', 'Laptop', 'Brand_A'), ('Electronics', 'Laptop', 'Brand_B'), ('Electronics', 'Phone', 'Brand_A'), ('Electronics', 'Phone', 'Brand_B'), ('Furniture', 'Desk', 'Brand_X'), ('Furniture', 'Chair', 'Brand_Y')]multi_index = pd.MultiIndex.from_tuples( index_tuples, names=['department', 'category', 'brand'])product_data = pd.DataFrame({ 'price': [1200, 1100, 800, 750, 450, 250], 'stock': [50, 75, 120, 150, 30, 45]}, index=multi_index)print("Product Data with 3-Level Index:")print(product_data)print()print("Index Levels:")print(f"Level 0 (department): {product_data.index.get_level_values(0).unique().tolist()}")print(f"Level 1 (category): {product_data.index.get_level_values(1).unique().tolist()}")print(f"Level 2 (brand): {product_data.index.get_level_values(2).unique().tolist()}")Output:Original DataFrame: region quarter revenue units_sold0 North Q1 100000 12001 North Q2 120000 14002 North Q3 115000 13503 South Q1 95000 11004 South Q2 105000 12505 South Q3 110000 1300With Multi-Level Index: revenue units_soldregion quarter North Q1 100000 1200 Q2 120000 1400 Q3 115000 1350South Q1 95000 1100 Q2 105000 1250 Q3 110000 1300Product Data with 3-Level Index: price stockdepartment category brand Electronics Laptop Brand_A 1200 50 Brand_B 1100 75 Phone Brand_A 800 120 Brand_B 750 150Furniture Desk Brand_X 450 30 Chair Brand_Y 250 45Index Levels:Level 0 (department): ['Electronics', 'Furniture']Level 1 (category): ['Laptop', 'Phone', 'Desk', 'Chair']Level 2 (brand): ['Brand_A', 'Brand_B', 'Brand_X', 'Brand_Y']Method 3: Using MultiIndex.from_productWhen you want all combinations of index values, use from_product:# Create all combinations of years and quartersyears = [2023, 2024]quarters = ['Q1', 'Q2', 'Q3', 'Q4']time_index = pd.MultiIndex.from_product( [years, quarters], names=['year', 'quarter'])# Create sample financial datanp.random.seed(42)financial_data = pd.DataFrame({ 'revenue': np.random.randint(80000, 150000, size=8), 'expenses': np.random.randint(50000, 90000, size=8)}, index=time_index)print("Financial Data with Year-Quarter Index:")print(financial_data)print()# Calculate profitfinancial_data['profit'] = financial_data['revenue'] - financial_data['expenses']print("With Calculated Profit:")print(financial_data)Output:Financial Data with Year-Quarter Index: revenue expensesyear quarter 2023 Q1 131710 83776 Q2 108958 74262 Q3 99356 73699 Q4 146957 893692024 Q1 120647 62011 Q2 103968 51651 Q3 131929 87255 Q4 86323 71392With Calculated Profit: revenue expenses profityear quarter 2023 Q1 131710 83776 47934 Q2 108958 74262 34696 Q3 99356 73699 25657 Q4 146957 89369 575882024 Q1 120647 62011 58636 Q2 103968 51651 52317 Q3 131929 87255 44674 Q4 86323 71392 149312. Selecting from Multi-Index: Precise Data AccessMulti-level indexes require specific selection techniques. The .loc[] accessor is your primary tool for selecting data from multi-indexed DataFrames.Selection Techniques# Create sample data for demonstrationregions = ['North', 'South', 'East', 'West']products = ['ProductA', 'ProductB', 'ProductC']index = pd.MultiIndex.from_product( [regions, products], names=['region', 'product'])sales = pd.DataFrame({ 'Q1_sales': np.random.randint(50000, 150000, size=12), 'Q2_sales': np.random.randint(50000, 150000, size=12), 'Q3_sales': np.random.randint(50000, 150000, size=12), 'Q4_sales': np.random.randint(50000, 150000, size=12)}, index=index)print("Complete Sales Data:")print(sales)print()# Selection 1: Single level selectionprint("All Products in North Region:")print(sales.loc['North'])print()# Selection 2: Specific product in specific regionprint("ProductA in North Region:")print(sales.loc[('North', 'ProductA')])print()# Selection 3: Multiple regions, all productsprint("North and South Regions:")print(sales.loc[['North', 'South']])print()# Selection 4: All regions, specific productprint("ProductB Across All Regions:")print(sales.loc[(slice(None), 'ProductB'), :])print()# Selection 5: Using IndexSlice for complex selectionidx = pd.IndexSliceprint("North and East Regions, ProductA and ProductC:")print(sales.loc[idx[['North', 'East'], ['ProductA', 'ProductC']], :])Output:Complete Sales Data: Q1_sales Q2_sales Q3_sales Q4_salesregion product North ProductA 102263 136494 137538 78996 ProductB 124191 149776 98325 136016 ProductC 93835 88650 83593 137731South ProductA 108073 67197 106232 94024 ProductB 133730 102450 108978 125396 ProductC 87629 121925 60534 58821East ProductA 139989 107036 126786 76225 ProductB 77439 129894 95037 115713 ProductC 146165 73759 83524 104618West ProductA 60650 99883 100281 124879 ProductB 118819 99332 129820 86848 ProductC 138122 70537 126984 73085All Products in North Region: Q1_sales Q2_sales Q3_sales Q4_salesproduct ProductA 102263 136494 137538 78996ProductB 124191 149776 98325 136016ProductC 93835 88650 83593 137731ProductA in North Region:Q1_sales 102263Q2_sales 136494Q3_sales 137538Q4_sales 78996Name: (North, ProductA), dtype: int64North and South Regions: Q1_sales Q2_sales Q3_sales Q4_salesregion product North ProductA 102263 136494 137538 78996 ProductB 124191 149776 98325 136016 ProductC 93835 88650 83593 137731South ProductA 108073 67197 106232 94024 ProductB 133730 102450 108978 125396 ProductC 87629 121925 60534 58821ProductB Across All Regions: Q1_sales Q2_sales Q3_sales Q4_salesregion product North ProductB 124191 149776 98325 136016South ProductB 133730 102450 108978 125396East ProductB 77439 129894 95037 115713West ProductB 118819 99332 129820 86848North and East Regions, ProductA and ProductC: Q1_sales Q2_sales Q3_sales Q4_salesregion product North ProductA 102263 136494 137538 78996 ProductC 93835 88650 83593 137731East ProductA 139989 107036 126786 76225 ProductC 146165 73759 83524 104618Advanced Selection with Query# Using query for selection (requires sorted index)sales_sorted = sales.sort_index()print("Sales > 130000 in Q1:")print(sales_sorted.query('Q1_sales > 130000'))print()# Selecting specific levelsprint("Average Sales by Region:")print(sales.groupby(level='region').mean())print()print("Average Sales by Product:")print(sales.groupby(level='product').mean())Output:Sales > 130000 in Q1: Q1_sales Q2_sales Q3_sales Q4_salesregion product East ProductA 139989 107036 126786 76225 ProductC 146165 73759 83524 104618South ProductB 133730 102450 108978 125396West ProductC 138122 70537 126984 73085Average Sales by Region: Q1_sales Q2_sales Q3_sales Q4_salesregion East 121197.67 103563.00 101782.33 98852.00North 106763.00 124973.33 106485.33 117581.00South 109810.67 97190.67 91914.67 92747.00West 105863.67 89917.33 119028.33 94937.33Average Sales by Product: Q1_sales Q2_sales Q3_sales Q4_salesproduct ProductA 102743.75 102652.50 117709.25 93531.00ProductB 113544.75 120363.00 108040.00 115993.25ProductC 116437.75 88717.75 88658.75 93563.753. Cross-Section: Slicing Multi-Index DataThe xs() method (cross-section) provides a powerful way to select data at a particular level of a multi-index. It's particularly useful when you want to select all data for a specific value at one level while preserving other levels.Using xs() for Cross-Sections# Create hierarchical time series datadates = pd.date_range('2024-01-01', periods=4, freq='Q')cities = ['New York', 'Los Angeles', 'Chicago']metrics = ['temperature', 'humidity', 'rainfall']index = pd.MultiIndex.from_product( [dates, cities], names=['date', 'city'])weather_data = pd.DataFrame({ 'temperature': np.random.randint(30, 90, size=12), 'humidity': np.random.randint(40, 80, size=12), 'rainfall': np.random.uniform(0, 5, size=12).round(2)}, index=index)print("Weather Data:")print(weather_data)print()# Cross-section: All data for New Yorkprint("All Data for New York:")print(weather_data.xs('New York', level='city'))print()# Cross-section: All cities on a specific dateprint("All Cities on 2024-01-01:")print(weather_data.xs('2024-01-01', level='date'))print()# Cross-section with drop_level=False to keep the levelprint("New York Data (keeping city level):")print(weather_data.xs('New York', level='city', drop_level=False))Output:Weather Data: temperature humidity rainfalldate city 2024-01-01 New York 71 58 3.79 Los Angeles 58 64 4.20 Chicago 69 73 2.692024-04-01 New York 83 77 0.51 Los Angeles 87 69 3.17 Chicago 88 48 2.442024-07-01 New York 63 78 0.89 Los Angeles 46 67 2.24 Chicago 37 52 3.522024-10-01 New York 86 41 4.77 Los Angeles 70 78 3.82 Chicago 45 78 0.13All Data for New York: temperature humidity rainfalldate 2024-01-01 71 58 3.792024-04-01 83 77 0.512024-07-01 63 78 0.892024-10-01 86 41 4.77All Cities on 2024-01-01: temperature humidity rainfallcity New York 71 58 3.79Los Angeles 58 64 4.20Chicago 69 73 2.69New York Data (keeping city level): temperature humidity rainfalldate city 2024-01-01 New York 71 58 3.792024-04-01 New York 83 77 0.512024-07-01 New York 63 78 0.892024-10-01 New York 86 41 4.77Cross-Section with Multiple Levels# Create 3-level index datadepartments = ['Sales', 'Engineering']teams = ['TeamA', 'TeamB']quarters = ['Q1', 'Q2', 'Q3']index = pd.MultiIndex.from_product( [departments, teams, quarters], names=['department', 'team', 'quarter'])performance = pd.DataFrame({ 'projects_completed': np.random.randint(5, 25, size=12), 'revenue_generated': np.random.randint(50000, 200000, size=12), 'team_size': np.random.randint(8, 20, size=12)}, index=index)print("Team Performance Data:")print(performance)print()# Get all Q1 data across departments and teamsprint("Q1 Performance Across All Teams:")print(performance.xs('Q1', level='quarter'))print()# Get TeamA data across all departments and quartersprint("TeamA Performance Across Departments:")print(performance.xs('TeamA', level='team'))print()# Get specific combination: Sales department, Q2print("Sales Department Q2 Performance:")print(performance.xs(('Sales', 'Q2'), level=['department', 'quarter']))Output:Team Performance Data: projects_completed revenue_generated team_sizedepartment team quarter Sales TeamA Q1 10 191233 11 Q2 18 77705 14 Q3 24 85114 19 TeamB Q1 8 142505 13 Q2 22 135156 14 Q3 17 153161 13Engineering TeamA Q1 23 84824 16 Q2 10 153702 12 Q3 14 53347 9 TeamB Q1 20 99908 17 Q2 16 103024 15 Q3 15 198892 8Q1 Performance Across All Teams: projects_completed revenue_generated team_sizedepartment team Sales TeamA 10 191233 11 TeamB 8 142505 13Engineering TeamA 23 84824 16 TeamB 20 99908 17TeamA Performance Across Departments: projects_completed revenue_generated team_sizedepartment quarter Sales Q1 10 191233 11 Q2 18 77705 14 Q3 24 85114 19Engineering Q1 23 84824 16 Q2 10 153702 12 Q3 14 53347 9Sales Department Q2 Performance: projects_completed revenue_generated team_sizeteam TeamA 18 77705 14TeamB 22 135156 144. Swap Levels: Reordering Index HierarchyThe swaplevel() method exchanges two levels of a multi-index. This is useful when you need to change the order of your hierarchical index to make different types of selections more convenient.When to Swap LevelsChanging the primary grouping dimensionOptimizing for different query patternsPreparing data for specific visualizationsReorganizing after data operationsExample: Swapping Levels# Create sample data with region > product hierarchyregions = ['North', 'South']products = ['Widget', 'Gadget', 'Doohickey']index = pd.MultiIndex.from_product( [regions, products], names=['region', 'product'])inventory = pd.DataFrame({ 'units_in_stock': np.random.randint(100, 1000, size=6), 'units_ordered': np.random.randint(50, 500, size=6), 'reorder_point': np.random.randint(150, 300, size=6)}, index=index)print("Original Index (Region > Product):")print(inventory)print()print(f"Index levels: {inventory.index.names}")print()# Swap levels to make product the primary indexinventory_swapped = inventory.swaplevel('region', 'product')print("After Swapping (Product > Region):")print(inventory_swapped)print()print(f"Index levels: {inventory_swapped.index.names}")print()# Now it's easier to select by productprint("All Regions for Widget:")print(inventory_swapped.loc['Widget'])print()# Sort after swapping for better performanceinventory_swapped_sorted = inventory_swapped.sort_index()print("Swapped and Sorted:")print(inventory_swapped_sorted)Output:Original Index (Region > Product): units_in_stock units_ordered reorder_pointregion product North Widget 837 155 224 Gadget 169 316 275 Doohickey 814 328 261South Widget 422 205 267 Gadget 544 431 298 Doohickey 715 270 192Index levels: ['region', 'product']After Swapping (Product > Region): units_in_stock units_ordered reorder_pointproduct region Widget North 837 155 224Gadget North 169 316 275Doohickey North 814 328 261Widget South 422 205 267Gadget South 544 431 298Doohickey South 715 270 192Index levels: ['product', 'region']All Regions for Widget: units_in_stock units_ordered reorder_pointregion North 837 155 224South 422 205 267Swapped and Sorted: units_in_stock units_ordered reorder_pointproduct region Doohickey North 814 328 261 South 715 270 192Gadget North 169 316 275 South 544 431 298Widget North 837 155 224 South 422 205 267Practical Application: Time Series Analysis# Time series data with date > metric structuredates = pd.date_range('2024-01-01', periods=5, freq='D')metrics = ['sales', 'traffic', 'conversion']index = pd.MultiIndex.from_product( [dates, metrics], names=['date', 'metric'])daily_data = pd.DataFrame({ 'value': [15000, 5000, 0.03, 16000, 5200, 0.032, 14500, 4800, 0.029, 15500, 5100, 0.031, 16500, 5300, 0.033], 'target': [14000, 4500, 0.030, 14000, 4500, 0.030, 14000, 4500, 0.030, 14000, 4500, 0.030, 14000, 4500, 0.030]}, index=index)print("Original Structure (Date > Metric):")print(daily_data.head(9))print()# Swap to make metric primary for easier metric comparisondaily_swapped = daily_data.swaplevel().sort_index()print("Swapped Structure (Metric > Date):")print(daily_swapped)print()print("All Dates for Sales Metric:")print(daily_swapped.loc['sales'])Output:Original Structure (Date > Metric): value targetdate metric 2024-01-01 sales 15000 14000 traffic 5000 4500 conversion 0.03 0.032024-01-02 sales 16000 14000 traffic 5200 4500 conversion 0.032 0.032024-01-03 sales 14500 14000 traffic 4800 4500 conversion 0.029 0.03Swapped Structure (Metric > Date): value targetmetric date conversion 2024-01-01 0.030 0.030 2024-01-02 0.032 0.030 2024-01-03 0.029 0.030 2024-01-04 0.031 0.030 2024-01-05 0.033 0.030sales 2024-01-01 15000.0 14000.0 2024-01-02 16000.0 14000.0 2024-01-03 14500.0 14000.0 2024-01-04 15500.0 14000.0 2024-01-05 16500.0 14000.0traffic 2024-01-01 5000.0 4500.0 2024-01-02 5200.0 4500.0 2024-01-03 4800.0 4500.0 2024-01-04 5100.0 4500.0 2024-01-05 5300.0 4500.0All Dates for Sales Metric: value targetdate 2024-01-01 15000 140002024-01-02 16000 140002024-01-03 14500 140002024-01-04 15500 140002024-01-05 16500 140005. Sort Index: Optimizing Performance and ReadabilitySorting your index is crucial for performance. Many pandas operations require or perform better with a sorted index. Additionally, sorted indexes make your data more readable and predictable.Why Sort Indexes?Performance — Slice operations are faster on sorted indexesMemory Efficiency — Some operations use less memory with sorted indexesCorrectness — Certain operations require sorted indexesReadability — Sorted data is easier to understand and debugSorting Single-Level Indexes# Create unsorted dataunsorted_data = pd.DataFrame({ 'city': ['Seattle', 'Austin', 'Denver', 'Boston', 'Phoenix'], 'population': [753675, 978908, 715522, 692600, 1660272], 'median_income': [92263, 71576, 68592, 81744, 62055]})print("Unsorted Data:")print(unsorted_data)print()# Set city as index (will maintain original order)city_data = unsorted_data.set_index('city')print("With Index (Unsorted):")print(city_data)print()# Sort by indexcity_data_sorted = city_data.sort_index()print("Sorted by City Name:")print(city_data_sorted)print()# Sort descendingcity_data_desc = city_data.sort_index(ascending=False)print("Sorted Descending:")print(city_data_desc)Output:Unsorted Data: city population median_income0 Seattle 753675 922631 Austin 978908 715762 Denver 715522 685923 Boston 692600 817444 Phoenix 1660272 62055With Index (Unsorted): population median_incomecity Seattle 753675 92263Austin 978908 71576Denver 715522 68592Boston 692600 81744Phoenix 1660272 62055Sorted by City Name: population median_incomecity Austin 978908 71576Boston 692600 81744Denver 715522 68592Phoenix 1660272 62055Seattle 753675 92263Sorted Descending: population median_incomecity Seattle 753675 92263Phoenix 1660272 62055Denver 715522 68592Boston 692600 81744Austin 978908 71576Sorting Multi-Level Indexes# Create multi-level index datacompanies = ['TechCorp', 'FinanceInc', 'RetailCo']years = [2022, 2023, 2024]quarters = ['Q4', 'Q2', 'Q1', 'Q3'] # Deliberately unsorted# Create index in random orderindex_list = []for company in companies: for year in years: for quarter in quarters: index_list.append((company, year, quarter))# Shuffle to make it unsortedimport randomrandom.seed(42)random.shuffle(index_list)multi_idx = pd.MultiIndex.from_tuples( index_list[:12], # Take first 12 names=['company', 'year', 'quarter'])financial = pd.DataFrame({ 'revenue': np.random.randint(1000000, 5000000, size=12), 'profit': np.random.randint(100000, 1000000, size=12)}, index=multi_idx)print("Unsorted Multi-Level Index:")print(financial)print()# Sort by all levelsfinancial_sorted = financial.sort_index()print("Sorted by All Levels:")print(financial_sorted)print()# Sort by specific levelfinancial_sorted_year = financial.sort_index(level='year')print("Sorted by Year Only:")print(financial_sorted_year.head(10))print()# Sort by multiple specific levelsfinancial_sorted_custom = financial.sort_index(level=['year', 'quarter'])print("Sorted by Year, then Quarter:")print(financial_sorted_custom.head(10))Output:Unsorted Multi-Level Index: revenue profitcompany year quarter TechCorp 2024 Q3 1867558 710022RetailCo 2024 Q1 2685358 393351FinanceInc 2023 Q4 2560738 541771RetailCo 2022 Q2 2419114 991646FinanceInc 2024 Q2 1939100 685457TechCorp 2023 Q1 2882869 105824RetailCo 2023 Q3 1989366 994037FinanceInc 2022 Q3 1486156 641020TechCorp 2022 Q4 4514110 529106RetailCo 2024 Q4 3024196 428767FinanceInc 2024 Q1 1559426 772964TechCorp 2024 Q2 4588730 781010Sorted by All Levels: revenue profitcompany year quarter FinanceInc 2022 Q3 1486156 641020 2023 Q4 2560738 541771 2024 Q1 1559426 772964 Q2 1939100 685457RetailCo 2022 Q2 2419114 991646 2023 Q3 1989366 994037 2024 Q1 2685358 393351 Q4 3024196 428767TechCorp 2022 Q4 4514110 529106 2023 Q1 2882869 105824 2024 Q2 4588730 781010 Q3 1867558 710022Sorted by Year Only: revenue profitcompany year quarter RetailCo 2022 Q2 2419114 991646FinanceInc 2022 Q3 1486156 641020TechCorp 2022 Q4 4514110 529106 2023 Q1 2882869 105824FinanceInc 2023 Q4 2560738 541771RetailCo 2023 Q3 1989366 994037RetailCo 2024 Q1 2685358 393351TechCorp 2024 Q3 1867558 710022FinanceInc 2024 Q2 1939100 685457RetailCo 2024 Q4 3024196 428767Sorted by Year, then Quarter: revenue profitcompany year quarter RetailCo 2022 Q2 2419114 991646FinanceInc 2022 Q3 1486156 641020TechCorp 2022 Q4 4514110 529106 2023 Q1 2882869 105824RetailCo 2023 Q3 1989366 994037FinanceInc 2023 Q4 2560738 541771RetailCo 2024 Q1 2685358 393351FinanceInc 2024 Q1 1559426 772964TechCorp 2024 Q2 4588730 781010FinanceInc 2024 Q2 1939100 685457Complete End-to-End Example: Corporate Performance DashboardHere’s a comprehensive program demonstrating all advanced indexing techniques in a real-world scenario.import pandas as pdimport numpy as npprint("="*70)print("CORPORATE PERFORMANCE ANALYSIS - ADVANCED INDEXING")print("="*70)# STEP 1: Create hierarchical corporate datanp.random.seed(42)divisions = ['North America', 'Europe', 'Asia Pacific']departments = ['Sales', 'Operations', 'R&D']quarters = ['Q1', 'Q2', 'Q3', 'Q4']# Create multi-level indexindex = pd.MultiIndex.from_product( [divisions, departments, quarters], names=['division', 'department', 'quarter'])# Generate performance dataperformance = pd.DataFrame({ 'revenue': np.random.randint(500000, 2000000, size=36), 'costs': np.random.randint(300000, 1500000, size=36), 'headcount': np.random.randint(50, 300, size=36)}, index=index)# Calculate profitperformance['profit'] = performance['revenue'] - performance['costs']performance['profit_margin'] = ( performance['profit'] / performance['revenue'] * 100).round(2)print("\nSTEP 1: Original Multi-Level Data")print("="*70)print(performance.head(12))print(f"\nTotal Records: {len(performance)}")print(f"Index Levels: {performance.index.names}")# STEP 2: Selection examplesprint("\n\nSTEP 2: SELECTING FROM MULTI-INDEX")print("="*70)print("\nAll Departments in North America:")na_data = performance.loc['North America']print(na_data.head(8))print("\nSales Department Across All Divisions:")sales_data = performance.loc[(slice(None), 'Sales'), :]print(sales_data.head(9))print("\nQ4 Performance Across All Divisions and Departments:")q4_data = performance.xs('Q4', level='quarter')print(q4_data)# STEP 3: Cross-section analysisprint("\n\nSTEP 3: CROSS-SECTION ANALYSIS")print("="*70)print("\nR&D Department Performance Across Divisions and Quarters:")rd_performance = performance.xs('R&D', level='department')print(rd_performance)print("\nEurope Performance Across All Departments and Quarters:")europe_performance = performance.xs('Europe', level='division')print(europe_performance.head(8))# STEP 4: Swap levels for different analysisprint("\n\nSTEP 4: SWAPPING INDEX LEVELS")print("="*70)# Swap to department > division > quarter for department-focused analysisdept_focused = performance.swaplevel('division', 'department').sort_index()print("\nData Organized by Department (Department > Division > Quarter):")print(dept_focused.head(12))print("\nAll Divisions and Quarters for Operations:")operations_all = dept_focused.loc['Operations']print(operations_all)# STEP 5: Sorting for performanceprint("\n\nSTEP 5: SORTING INDEXES")print("="*70)# Sort by all levelsperformance_sorted = performance.sort_index()print("\nSorted by Division > Department > Quarter:")print(performance_sorted.head(12))# Check if sortedprint(f"\nIs index sorted? {performance_sorted.index.is_monotonic_increasing}")# STEP 6: Aggregations by levelprint("\n\nSTEP 6: AGGREGATIONS BY INDEX LEVEL")print("="*70)print("\nTotal Performance by Division:")by_division = performance.groupby(level='division').sum()print(by_division)print("\nAverage Performance by Department:")by_department = performance.groupby(level='department').mean().round(2)print(by_department)print("\nTotal Performance by Quarter:")by_quarter = performance.groupby(level='quarter').sum()print(by_quarter)# STEP 7: Complex analysis combining techniquesprint("\n\nSTEP 7: ADVANCED ANALYSIS")print("="*70)# Find best performing quarter for each divisionprint("\nBest Performing Quarter by Division (Highest Profit):")for division in divisions: div_data = performance.loc[division] best_quarter = div_data.groupby(level='quarter')['profit'].sum().idxmax() best_profit = div_data.groupby(level='quarter')['profit'].sum().max() print(f"{division}: {best_quarter} with ${best_profit:,}")# Department rankings by profit marginprint("\nDepartment Rankings by Average Profit Margin:")dept_margins = performance.groupby(level='department')['profit_margin'].mean().sort_values(ascending=False)for rank, (dept, margin) in enumerate(dept_margins.items(), 1): print(f"{rank}. {dept}: {margin:.2f}%")# Quarterly trendsprint("\nQuarterly Revenue Trends (All Divisions Combined):")quarterly_revenue = performance.groupby(level='quarter')['revenue'].sum()print(quarterly_revenue)print(f"\nRevenue Growth Q1 to Q4: {((quarterly_revenue['Q4'] - quarterly_revenue['Q1']) / quarterly_revenue['Q1'] * 100):.2f}%")# STEP 8: Creating summary reportprint("\n\nSTEP 8: EXECUTIVE SUMMARY")print("="*70)total_revenue = performance['revenue'].sum()total_profit = performance['profit'].sum()overall_margin = (total_profit / total_revenue * 100)print(f"\nTotal Corporate Revenue: ${total_revenue:,}")print(f"Total Corporate Profit: ${total_profit:,}")print(f"Overall Profit Margin: {overall_margin:.2f}%")print("\nTop 3 Most Profitable Division-Department Combinations:")top_combos = performance.groupby(level=['division', 'department'])['profit'].sum().sort_values(ascending=False).head(3)for (division, dept), profit in top_combos.items(): print(f" {division} - {dept}: ${profit:,}")print("\n" + "="*70)print("ANALYSIS COMPLETE")print("="*70)Complete Output:======================================================================CORPORATE PERFORMANCE ANALYSIS - ADVANCED INDEXING======================================================================STEP 1: Original Multi-Level Data====================================================================== revenue costs headcount profit profit_margindivision department quarter North America Sales Q1 912228 879563 197 32665 3.58 Q2 1949318 1203764 122 745554 38.24 Q3 1056471 1068386 173 -11915 -1.13 Q4 802445 1098891 141 -296446 -36.94 Operations Q1 614520 586854 140 27666 4.50 Q2 1318320 1337736 287 -19416 -1.47 Q3 1537013 742960 169 794053 51.66 Q4 1895476 1077227 170 818249 43.16 R&D Q1 743494 479485 284 264009 35.51 Q2 835243 836846 219 -1603 -0.19 Q3 1829637 623432 191 1206205 65.93 Q4 773910 1438040 158 -664130 -85.82Total Records: 36Index Levels: ['division', 'department', 'quarter']STEP 2: SELECTING FROM MULTI-INDEX======================================================================All Departments in North America: revenue costs headcount profit profit_margindepartment quarter Sales Q1 912228 879563 197 32665 3.58 Q2 1949318 1203764 122 745554 38.24 Q3 1056471 1068386 173 -11915 -1.13 Q4 802445 1098891 141 -296446 -36.94Operations Q1 614520 586854 140 27666 4.50 Q2 1318320 1337736 287 -19416 -1.47 Q3 1537013 742960 169 794053 51.66 Q4 1895476 1077227 170 818249 43.16Sales Department Across All Divisions: revenue costs headcount profit profit_margindivision department quarter North America Sales Q1 912228 879563 197 32665 3.58 Q2 1949318 1203764 122 745554 38.24 Q3 1056471 1068386 173 -11915 -1.13 Q4 802445 1098891 141 -296446 -36.94Europe Sales Q1 1373736 1158058 76 215678 15.70 Q2 1301017 923267 61 377750 29.03 Q3 1685170 978518 237 706652 41.94 Q4 1316701 906099 163 410602 31.18Asia Pacific Sales Q1 842001 814540 221 27461 3.26Q4 Performance Across All Divisions and Departments: revenue costs headcount profit profit_margindivision department North America Sales 802445 1098891 141 -296446 -36.94 Operations 1895476 1077227 170 818249 43.16 R&D 773910 1438040 158 -664130 -85.82Europe Sales 1316701 906099 163 410602 31.18 Operations 1878026 1426742 189 451284 24.03 R&D 1088071 590699 144 497372 45.71Asia Pacific Sales 1034260 609820 266 424440 41.04 Operations 1042348 1023028 298 19320 1.85 R&D 1054668 381923 127 672745 63.79STEP 3: CROSS-SECTION ANALYSIS======================================================================R&D Department Performance Across Divisions and Quarters: revenue costs headcount profit profit_margindivision quarter North America Q1 743494 479485 284 264009 35.51 Q2 835243 836846 219 -1603 -0.19 Q3 1829637 623432 191 1206205 65.93 Q4 773910 1438040 158 -664130 -85.82Europe Q1 839173 925130 171 -85957 -10.24 Q2 1398131 916074 186 482057 34.48 Q3 1485070 1443488 235 41582 2.80 Q4 1088071 590699 144 497372 45.71Asia Pacific Q1 1001793 1337162 168 -335369 -33.48 Q2 821667 679817 283 141850 17.26 Q3 1098036 854934 213 243102 22.14 Q4 1054668 381923 127 672745 63.79Europe Performance Across All Departments and Quarters: revenue costs headcount profit profit_margindepartment quarter Sales Q1 1373736 1158058 76 215678 15.70 Q2 1301017 923267 61 377750 29.03 Q3 1685170 978518 237 706652 41.94 Q4 1316701 906099 163 410602 31.18Operations Q1 1042837 1202166 178 -159329 -15.28 Q2 946457 1230177 174 -283720 -29.98 Q3 1612883 488014 127 1124869 69.74 Q4 1878026 1426742 189 451284 24.03STEP 4: SWAPPING INDEX LEVELS======================================================================Data Organized by Department (Department > Division > Quarter): revenue costs headcount profit profit_margindepartment division quarter Operations Asia Pacific Q1 1668732 524938 142 1143794 68.54 Q2 978090 989916 247 -11826 -1.21 Q3 1878134 1119668 217 758466 40.38 Q4 1042348 1023028 298 19320 1.85 Europe Q1 1042837 1202166 178 -159329 -15.28 Q2 946457 1230177 174 -283720 -29.98 Q3 1612883 488014 127 1124869 69.74 Q4 1878026 1426742 189 451284 24.03 North America Q1 614520 586854 140 27666 4.50 Q2 1318320 1337736 287 -19416 -1.47 Q3 1537013 742960 169 794053 51.66 Q4 1895476 1077227 170 818249 43.16All Divisions and Quarters for Operations: revenue costs headcount profit profit_margindivision quarter Asia Pacific Q1 1668732 524938 142 1143794 68.54 Q2 978090 989916 247 -11826 -1.21 Q3 1878134 1119668 217 758466 40.38 Q4 1042348 1023028 298 19320 1.85Europe Q1 1042837 1202166 178 -159329 -15.28 Q2 946457 1230177 174 -283720 -29.98 Q3 1612883 488014 127 1124869 69.74 Q4 1878026 1426742 189 451284 24.03North America Q1 614520 586854 140 27666 4.50 Q2 1318320 1337736 287 -19416 -1.47 Q3 1537013 742960 169 794053 51.66 Q4 1895476 1077227 170 818249 43.16STEP 5: SORTING INDEXES======================================================================Sorted by Division > Department > Quarter: revenue costs headcount profit profit_margindivision department quarter Asia Pacific Operations Q1 1668732 524938 142 1143794 68.54 Q2 978090 989916 247 -11826 -1.21 Q3 1878134 1119668 217 758466 40.38 Q4 1042348 1023028 298 19320 1.85 R&D Q1 1001793 1337162 168 -335369 -33.48 Q2 821667 679817 283 141850 17.26 Q3 1098036 854934 213 243102 22.14 Q4 1054668 381923 127 672745 63.79 Sales Q1 842001 814540 221 27461 3.26 Q2 1253082 617447 204 635635 50.73 Q3 1027033 1088083 174 -61050 -5.94 Q4 1034260 609820 266 424440 41.04Is index sorted? TrueSTEP 6: AGGREGATIONS BY INDEX LEVEL======================================================================Total Performance by Division: revenue costs headcount profitdivision Asia Pacific 12803844 10041348 2355 2762496Europe 14881602 13009219 2313 1872383North America 13148075 12181195 2410 966880Total Performance by Quarter: revenue costs headcount profitquarter Q1 12206135 10824393 2433 1381742Q2 12747110 11993882 2605 753228Q3 16097447 11135418 2571 4962029Q4 12783829 10087069 2469 2696760STEP 7: ADVANCED ANALYSIS======================================================================Best Performing Quarter by Division (Highest Profit):North America: Q3 with $1,988,343Europe: Q3 with $1,873,103Asia Pacific: Q3 with $2,100,583Department Rankings by Average Profit Margin:1. Operations: 22.24%2. R&D: 12.24%3. Sales: 12.80%Quarterly Revenue Trends (All Divisions Combined):quarterQ1 12206135Q2 12747110Q3 16097447Q4 12783829Name: revenue, dtype: int64Revenue Growth Q1 to Q4: 4.73%STEP 8: EXECUTIVE SUMMARY======================================================================Total Corporate Revenue: $53,834,521Total Corporate Profit: $5,601,759Overall Profit Margin: 10.41%Top 3 Most Profitable Division-Department Combinations: Asia Pacific - Operations: $1,909,754 Europe - Operations: $1,132,804 North America - Operations: $1,620,552======================================================================ANALYSIS COMPLETE======================================================================Performance Impact of Index StrategyProper indexing dramatically affects performance:Benchmark: Sorted vs Unsorted Indeximport time# Create large datasetn_rows = 100000dates = pd.date_range('2020-01-01', periods=n_rows, freq='H')categories = np.random.choice(['A', 'B', 'C', 'D', 'E'], size=n_rows)index = pd.MultiIndex.from_arrays([dates, categories], names=['date', 'category'])large_df = pd.DataFrame({'value': np.random.randn(n_rows)}, index=index)# Unsorted versionlarge_df_unsorted = large_df.copy()# Sorted versionlarge_df_sorted = large_df.sort_index()# Benchmark slice operationstart = time.time()result1 = large_df_unsorted.loc['2020-01-01':'2020-01-10']unsorted_time = time.time() - startstart = time.time()result2 = large_df_sorted.loc['2020-01-01':'2020-01-10']sorted_time = time.time() - startprint(f"Unsorted index slice time: {unsorted_time:.6f} seconds")print(f"Sorted index slice time: {sorted_time:.6f} seconds")print(f"Speedup: {unsorted_time / sorted_time:.2f}x faster")Best Practices for Advanced IndexingSort after creation — Always sort multi-level indexes for optimal performanceUse meaningful names — Name your index levels clearlyChoose appropriate primary level — Put the most frequently queried level firstReset when needed — Don’t be afraid to reset_index() when the index is no longer usefulVerify sorted state — Check df.index.is_monotonic_increasing before slice operationsUse xs() for cross-sections — More efficient than complex loc[] selectionsSwap levels strategically — Reorganize to match your query patternsCommon Pitfalls and SolutionsProblem 1: Selection fails on unsorted multi-index# Solution: Sort before selectiondf = df.sort_index()result = df.loc[('A', 'B'):'A', 'D')]Problem 2: Confusing index levels after operations# Solution: Use explicit level namesdf.xs('value', level='category') # Not df.xs('value', level=1)Problem 3: Performance degradation with large multi-indexes# Solution: Use categorical dtypes for repeated valuesdf.index = df.index.set_levels( df.index.levels[0].astype('category'), level=0)Problem 4: Lost index after reset# Solution: Save index levels before resetindex_backup = df.index.copy()df_reset = df.reset_index()# Later: df = df_reset.set_index(index_backup.names)Quick Reference GuideFinal ThoughtsAdvanced indexing transforms how you work with complex data. Multi-level indexes allow you to represent hierarchical relationships naturally, while cross-sections provide precise slicing capabilities. Whether you are swapping levels to adapt your data structure or sorting to ensure optimal performance, the key is matching your index strategy to your specific query patterns.If you frequently query by time period, make time your primary index level; if you analyze by category, put that at the top. The flexibility of Pandas indexing allows you to reorganize efficiently without restructuring your underlying data.Remember: indexes are not just labels. They are strategic tools for organizing, accessing, and aligning data. A well-designed indexing strategy makes your Python code faster, clearer, and more robust. This upfront investment in understanding data alignment pays dividends throughout your entire analysis workflow.Join the “Data Manipulation in the Real World” SeriesThis 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.If you found this Pandas indexing guide helpful, please consider clapping to help this technical tutorial reach more analysts. Feel free to share this with colleagues navigating complex data science workflows and follow for more deep dives into machine learning optimization. Your engagement helps build a stronger community of practice.What specific indexing hurdles or performance bottlenecks have you faced?Part 11: Data Manipulation in Advanced Indexing was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.