MODULE 4.4: PIVOT TABLES, CROSSTABS & DATA RESHAPING METHODS

Master the art of transforming tabular layouts in Python. Learn how to build Excel-style pivot tables, frequency crosstabs, unpivot wide data with `melt`, and pivot long data with `stack` and `unstack` across 10 real-world examples.

πŸ’‘ Understanding Data Reshaping in Pandas

Data comes in many shapesβ€”some formats are optimized for relational storage (long/tidy format), while others are optimized for human readability and executive reporting (wide/pivot format). Pandas provides powerful functions to convert data between these layouts instantly:

1. `pivot_table()`: Aggregates and summarizes data across two axes (rows and columns).
2. `crosstab()`: Computes a simple or frequency cross-tabulation of two or more factors.
3. `melt()`: Unpivots a wide DataFrame into a long format.
4. `stack()` & `unstack()`: Rotates or pivots data between columns and multi-level indexes.

1. Creating a Basic Pivot Table (`df.pivot_table`)
Summarizing total sales revenue grouped by City (rows) and Product Category (columns).
Python (basic_pivot.py)
import pandas as pd

def basic_pivot_demo():
    data = {
        'City': ['New York', 'New York', 'London', 'London', 'Paris', 'Paris'],
        'Category': ['Electronics', 'Clothing', 'Electronics', 'Clothing', 'Electronics', 'Clothing'],
        'Sales': [500, 200, 800, 300, 400, 150]
    }
    df = pd.DataFrame(data)
    
    # Pivot table summing sales
    pivot = df.pivot_table(index='City', columns='Category', values='Sales', aggfunc='sum')
    print("--- City vs Category Sales Pivot ---")
    print(pivot)

basic_pivot_demo()
Output: --- City vs Category Sales Pivot --- Category Clothing Electronics City London 300 800 New York 200 500 Paris 150 400
2. Pivot Table with Multiple Aggregation Functions (`aggfunc`)
Computing both the sum and average sales simultaneously for regional store data.
Python (multi_agg_pivot.py)
import pandas as pd

def multi_agg_pivot():
    data = {
        'Region': ['East', 'East', 'West', 'West', 'East', 'West'],
        'Rep': ['Alice', 'Bob', 'Charlie', 'David', 'Alice', 'David'],
        'Sales': [1000, 1500, 800, 2000, 1200, 2500]
    }
    df = pd.DataFrame(data)
    
    pivot = df.pivot_table(index='Region', values='Sales', aggfunc=['sum', 'mean'])
    print("--- Multi-Aggregation Pivot ---")
    print(pivot)

multi_agg_pivot()
Output: --- Multi-Aggregation Pivot --- sum mean Sales Sales Region East 3700 1233.333333 West 5300 1766.666667
3. Handling Missing Values in Pivots Using `fill_value`
Replacing `NaN` resulting from empty combinations with a clean default value like `0` or `N/A`.
Python (fill_value_pivot.py)
import pandas as pd

def fill_value_demo():
    data = {
        'Month': ['Jan', 'Jan', 'Feb'],
        'Product': ['Laptop', 'Phone', 'Laptop'],
        'Units': [10, 25, 15]
    }
    df = pd.DataFrame(data)
    
    # Phone was not sold in Feb, resulting in NaN without fill_value
    pivot = df.pivot_table(index='Month', columns='Product', values='Units', fill_value=0)
    print("--- Pivot with Filled NaNs ---")
    print(pivot)

fill_value_demo()
Output: --- Pivot with Filled NaNs --- Product Laptop Phone Month Feb 15 0 Jan 10 25
4. Frequency Cross-Tabulation (`pd.crosstab`)
Counting the frequency of customer subscription types across different age groups.
Python (crosstab_demo.py)
import pandas as pd

def crosstab_demo():
    data = {
        'AgeGroup': ['Young', 'Adult', 'Senior', 'Young', 'Adult', 'Senior', 'Young'],
        'Plan': ['Basic', 'Premium', 'Basic', 'Premium', 'Premium', 'Basic', 'Basic']
    }
    df = pd.DataFrame(data)
    
    ct = pd.crosstab(df['AgeGroup'], df['Plan'])
    print("--- Frequency Crosstab ---")
    print(ct)

crosstab_demo()
Output: --- Frequency Crosstab --- Plan Basic Premium AgeGroup Adult 0 2 Senior 2 0 Young 2 1
5. Crosstab with Margins (Totals)
Adding row and column marginal totals (`margins=True`) to frequency cross-tabulations.
Python (crosstab_margins.py)
import pandas as pd

def crosstab_margins():
    data = {
        'Department': ['HR', 'IT', 'IT', 'HR', 'Sales', 'Sales'],
        'Performance': ['High', 'Medium', 'High', 'Low', 'High', 'Medium']
    }
    df = pd.DataFrame(data)
    
    ct = pd.crosstab(df['Department'], df['Performance'], margins=True, margins_name='Total')
    print("--- Crosstab with Margins ---")
    print(ct)

crosstab_margins()
Output: --- Crosstab with Margins --- Performance High Low Medium Total Department HR 1 1 0 2 IT 2 0 1 3 Sales 1 0 1 2 Total 4 1 2 7
6. Unpivoting Wide Data Using `pd.melt()`
Converting a wide annual sales report (columns for each year) into a clean, tidy long-format table.
Python (melt_wide_data.py)
import pandas as pd

def melt_demo():
    wide_df = pd.DataFrame({
        'Country': ['USA', 'India', 'Germany'],
        '2023': [100, 150, 120],
        '2024': [110, 180, 130]
    })
    
    long_df = pd.melt(wide_df, id_vars=['Country'], value_vars=['2023', '2024'], var_name='Year', value_name='GDP')
    print("--- Unpivoted Long Format ---")
    print(long_df.to_string(index=False))

melt_demo()
Output: --- Unpivoted Long Format --- Country Year GDP USA 2023 100 India 2023 150 Germany 2023 120 USA 2024 110 India 2024 180 Germany 2024 130
7. Rotating Index Levels Using `.stack()`
Pivoting columns into rows to reshape a DataFrame into a Series with a MultiIndex.
Python (stack_demo.py)
import pandas as pd

def stack_demo():
    df = pd.DataFrame({
        'Math': [85, 90],
        'Science': [92, 88]
    }, index=['Alice', 'Bob'])
    
    print("--- Original DataFrame ---")
    print(df)
    
    stacked = df.stack()
    print("\n--- Stacked Series ---")
    print(stacked)

stack_demo()
Output: --- Original DataFrame --- Math Science Alice 85 92 Bob 90 88 --- Stacked Series --- Alice Math 85 Science 92 Bob Math 90 Science 88 dtype: int64
8. Rotating MultiIndex Rows Back to Columns Using `.unstack()`
The inverse of `stack()`β€”pivoting innermost row indices back out into column headers.
Python (unstack_demo.py)
import pandas as pd

def unstack_demo():
    # Creating a stacked series from previous example
    index = pd.MultiIndex.from_tuples([('Alice', 'Math'), ('Alice', 'Science'), ('Bob', 'Math'), ('Bob', 'Science')])
    stacked = pd.Series([85, 92, 90, 88], index=index)
    
    unstacked = stacked.unstack()
    print("--- Unstacked DataFrame ---")
    print(unstacked)

unstack_demo()
Output: --- Unstacked DataFrame --- Math Science Alice 85 92 Bob 90 88
9. Complex Hierarchical Pivot with Multiple Index Levels
Building complex executive dashboards using multi-level row grouping in `pivot_table()`.
Python (hierarchical_pivot.py)
import pandas as pd

def hierarchical_pivot():
    data = {
        'Region': ['East', 'East', 'West', 'West', 'East', 'West'],
        'Store': ['Store_A', 'Store_B', 'Store_C', 'Store_D', 'Store_A', 'Store_C'],
        'Category': ['Tech', 'Tech', 'Tech', 'Tech', 'Apparel', 'Apparel'],
        'Revenue': [5000, 3000, 7000, 4000, 2000, 1500]
    }
    df = pd.DataFrame(data)
    
    pivot = df.pivot_table(index=['Region', 'Store'], columns='Category', values='Revenue', fill_value=0)
    print("--- Hierarchical Multi-Level Pivot ---")
    print(pivot)

hierarchical_pivot()
Output: --- Hierarchical Multi-Level Pivot --- Category Apparel Tech Region Store East Store_A 2000 5000 Store_B 0 3000 West Store_C 1500 7000 Store_D 0 4000
10. End-to-End Sales Data Reshaping Pipeline
Complete pipeline melting wide quarterly metrics, performing pivot aggregations, and cleaning up indexes for reporting.
Python (reshaping_pipeline.py)
import pandas as pd

def sales_reshaping_pipeline():
    raw_wide = pd.DataFrame({
        'Product': ['Phone', 'Laptop'],
        'Q1': [1200, 4500],
        'Q2': [1500, 4800],
        'Q3': [1300, 5200],
        'Q4': [1900, 6100]
    })
    
    # Step 1: Melt into long format
    long_df = pd.melt(raw_wide, id_vars=['Product'], var_name='Quarter', value_name='Sales')
    
    # Step 2: Pivot to reorganize by Quarter vs Product
    final_report = long_df.pivot_table(index='Quarter', columns='Product', values='Sales')
    
    print("--- Final Reshaped Executive Report ---")
    print(final_report)

sales_reshaping_pipeline()
Output: --- Final Reshaped Executive Report --- Product Laptop Phone Quarter Q1 4500 1200 Q2 4800 1500 Q3 5200 1300 Q4 6100 1900