# Module 13: Advanced Pandas ## Learning Objectives By the end of this module, you will be able to: - Work with MultiIndex DataFrames for hierarchical data - Use window functions for advanced rolling computations - Manage categorical data efficiently with `CategoricalDtype` - Optimise performance with vectorisation and `numba` - Reduce memory usage with efficient dtypes and chunking --- ```{note} This module covers advanced techniques that separate beginner from proficient Pandas users. Mastering these concepts will enable you to work with larger datasets, write faster code, and model complex data structures. ``` ## MultiIndex (Hierarchical Indexing) A MultiIndex allows you to store and manipulate data with multiple levels of row or column labels. ### Creating a MultiIndex ```python import pandas as pd import numpy as np # From arrays arrays = [ ["North", "North", "South", "South", "East", "East"], ["Q1", "Q2", "Q1", "Q2", "Q1", "Q2"], ] index = pd.MultiIndex.from_arrays(arrays, names=["Region", "Quarter"]) df = pd.DataFrame({ "Sales": [100, 120, 150, 130, 90, 110], "Profit": [20, 25, 30, 28, 18, 22], }, index=index) print(df) ``` ### Creating from a tuple index ```python tuples = [ ("North", "Q1"), ("North", "Q2"), ("South", "Q1"), ("South", "Q2"), ("East", "Q1"), ("East", "Q2"), ] index = pd.MultiIndex.from_tuples(tuples, names=["Region", "Quarter"]) ``` ### Creating with `set_index()` ```python flat = pd.DataFrame({ "Region": ["North", "North", "South", "South"], "Quarter": ["Q1", "Q2", "Q1", "Q2"], "Sales": [100, 120, 150, 130], }) df_mi = flat.set_index(["Region", "Quarter"]) print(df_mi) ``` ### Indexing with MultiIndex ```python # Select all rows for a level value print(df.loc["North"]) # Select specific cross-section print(df.loc[("North", "Q1")]) # Select with xs (cross-section) print(df.xs("Q1", level="Quarter")) # Select multiple levels print(df.loc[("North", "Q1"), "Sales"]) ``` ### Sorting with MultiIndex ```python # Sorting is critical for slicing performance df_sorted = df.sort_index() print(df_sorted) # Slice after sorting print(df_sorted.loc["North":"South"]) ``` ```{tip} Always call `.sort_index()` on MultiIndex DataFrames before slicing. Unsorted indices can produce warnings or incorrect results with label-based slicing. ``` ### Unstack and stack ```python # Unstack (move inner index level to columns) print(df.unstack()) # Stack (move columns to inner index level) stacked = df.unstack().stack() print(stacked) ``` ### Multi-level columns ```python # MultiIndex columns col_arrays = [ ["Sales", "Sales", "Profit", "Profit"], ["Actual", "Budget", "Actual", "Budget"], ] df.columns = pd.MultiIndex.from_arrays(col_arrays) print(df) ``` ## Window Functions ### Custom rolling window functions ```python # Custom aggregation on rolling window np.random.seed(42) ts = pd.Series(np.random.randn(100).cumsum(), name="Value") # Define custom function def range_pct(series): return (series.max() - series.min()) / series.mean() * 100 result = ts.rolling(window=10).apply(range_pct, raw=False) print(result.head(15)) ``` ### Weighted moving average ```python # Custom weighted average def wma(series): weights = np.arange(1, len(series) + 1) return np.average(series, weights=weights) ts_wma = ts.rolling(window=10).apply(wma) ``` ### Expanding window operations ```python # Expanding with custom function expanding_range = ts.expanding().apply(lambda x: x.max() - x.min()) ``` ```{note} Window functions with `.apply()` are slower than built-in methods like `.mean()` or `.std()`. Use them only when you need custom logic that cannot be expressed with built-in window functions. ``` ## Categorical Data Categorical data saves memory and improves performance when you have repeated string values. ### Creating categorical data ```python # Convert to categorical df["Category"] = pd.Categorical( ["A", "B", "A", "C", "B", "A"], categories=["A", "B", "C", "D"], ordered=True, ) print(df["Category"].dtype) print(df["Category"].cat.categories) ``` ### Working with categories ```python # Reorder categories df["Category"] = df["Category"].cat.reorder_categories(["C", "B", "A", "D"]) # Rename categories df["Category"] = df["Category"].cat.rename_categories({"A": "Alpha", "B": "Beta"}) # Add new categories df["Category"] = df["Category"].cat.add_categories(["E"]) # Remove unused categories df["Category"] = df["Category"].cat.remove_unused_categories() ``` ### Memory comparison ```python import sys # Generate large dataset n = 1_000_000 str_series = pd.Series(np.random.choice(["Low", "Medium", "High", "Critical"], n)) cat_series = str_series.astype("category") str_memory = str_series.memory_usage(deep=True) cat_memory = cat_series.memory_usage(deep=True) print(f"String dtype: {str_memory / 1e6:.1f} MB") print(f"Categorical: {cat_memory / 1e6:.1f} MB") print(f"Savings: {(1 - cat_memory / str_memory) * 100:.1f}%") ``` ```{warning} Categorical data is most memory-efficient when the number of unique values is small relative to the total data size. For high-cardinality columns (e.g., unique IDs), categorical may use *more* memory than string. ``` ## Performance Optimization ### Vectorisation Vectorised operations are the fastest way to work with Pandas. ```python # SLOW: Row-wise apply def slow_approach(df): return df.apply(lambda row: row["A"] * row["B"] + row["C"], axis=1) # FAST: Vectorised def fast_approach(df): return df["A"] * df["B"] + df["C"] # Benchmark n = 100_000 bench_df = pd.DataFrame({ "A": np.random.randn(n), "B": np.random.randn(n), "C": np.random.randn(n), }) %timeit slow_approach(bench_df) %timeit fast_approach(bench_df) ``` ### Using `.values` or `.to_numpy()` ```python # Operating on raw NumPy arrays can be faster arr = bench_df[["A", "B", "C"]].to_numpy() result = arr[:, 0] * arr[:, 1] + arr[:, 2] ``` ### Using numba for compiled operations ```python from numba import jit @jit(nopython=True) def fast_calc(a, b, c): return a * b + c # Much faster for complex custom functions numpy_result = fast_calc( bench_df["A"].to_numpy(), bench_df["B"].to_numpy(), bench_df["C"].to_numpy(), ) ``` ```{tip} For operations that cannot be vectorised, consider using `numba` with `.to_numpy()` for 10-100x speedups compared to `.apply()`. ``` ### Using `itertuples()` instead of `iterrows()` ```python # iterrows() is very slow for idx, row in bench_df.head(1000).iterrows(): _ = row["A"] + row["B"] # itertuples() is much faster for row in bench_df.head(1000).itertuples(): _ = row.A + row.B # Access by attribute, not string ``` ## Memory Optimization ### Efficient dtypes ```python # Downcast numeric columns def optimize_numeric(df): for col in df.select_dtypes(include=["int", "float"]).columns: col_min = df[col].min() col_max = df[col].max() if pd.api.types.is_integer_dtype(df[col]): for dtype in ["int8", "int16", "int32", "int64"]: info = np.iinfo(dtype) if col_min >= info.min and col_max <= info.max: df[col] = df[col].astype(dtype) break else: for dtype in ["float32", "float64"]: info = np.finfo(dtype) if col_min >= info.min and col_max <= info.max: df[col] = df[col].astype(dtype) break return df optimized = optimize_numeric(bench_df.copy()) print(f"Original memory: {bench_df.memory_usage(deep=True).sum() / 1e6:.2f} MB") print(f"Optimized memory: {optimized.memory_usage(deep=True).sum() / 1e6:.2f} MB") ``` ### Reading data in chunks ```python # Process large files in chunks chunk_size = 10000 results = [] for chunk in pd.read_csv("large_file.csv", chunksize=chunk_size): # Process each chunk results.append(chunk.groupby("Category")["Value"].sum()) # Combine results final_result = pd.concat(results).groupby(level=0).sum() ``` ### Using `pd.read_csv()` optimisations ```python # Specify dtypes to avoid type inference overhead dtypes = { "id": "int32", "category": "category", "value": "float32", } # Only read needed columns df = pd.read_csv( "large_file.csv", usecols=["id", "category", "value", "date"], dtype=dtypes, parse_dates=["date"], low_memory=False, ) ``` ```{note} Specifying `dtypes` in `read_csv()` prevents Pandas from inferring types (which requires reading the entire file) and can significantly reduce both memory usage and loading time. ``` ## Practical Example: Optimising a Data Pipeline ```python def efficient_pipeline(filepath): """Memory-efficient data processing pipeline.""" # Define dtypes upfront dtypes = { "store_id": "int16", "product_id": "int32", "category": "category", "region": "category", "sales": "float32", "quantity": "int16", } # Read in chunks and aggregate aggregated = [] for chunk in pd.read_csv(filepath, dtype=dtypes, chunksize=50000, low_memory=True): # Drop rows with missing critical data chunk = chunk.dropna(subset=["sales", "store_id"]) # Summarise within chunk summary = chunk.groupby(["region", "category"], observed=True).agg( total_sales=("sales", "sum"), avg_sales=("sales", "mean"), total_qty=("quantity", "sum"), ) aggregated.append(summary) # Combine chunk summaries final = pd.concat(aggregated).groupby(level=[0, 1], observed=True).sum() return final # result = efficient_pipeline("sales_data_2024.csv") ``` ## Summary - MultiIndex enables hierarchical row and column labels for complex data structures - Use `.xs()`, `.loc[]`, and `.unstack()`/`.stack()` to navigate multi-level indices - Custom window functions with `.rolling().apply()` for advanced time series - Categorical dtypes reduce memory for low-cardinality string columns - Vectorised operations are orders of magnitude faster than `.apply(axis=1)` - Use `numba` for accelerating custom numerical operations - Downcast numeric types and use chunking for memory optimisation ## Exercises Using this dataset: ```python import pandas as pd import numpy as np np.random.seed(42) df = pd.DataFrame({ "Year": np.repeat([2020, 2021, 2022, 2023], 100), "Quarter": np.tile(["Q1", "Q2", "Q3", "Q4"], 100), "Product": np.random.choice(["A", "B", "C", "D"], 400), "Sales": np.round(np.random.uniform(100, 1000, 400), 2), "Cost": np.round(np.random.uniform(50, 500, 400), 2), }) ``` 1. Create a MultiIndex DataFrame with `Year` and `Quarter` as the index, then compute the mean Sales for each `Year` 2. Use `.xs()` to select all Q2 data across all years 3. Unstack the `Quarter` level so each quarter becomes a column 4. Convert `Product` to categorical dtype and compare memory usage 5. Create a profit column using vectorised operations (`Sales - Cost`) 6. Use a rolling window on a time series version of the data to compute a 4-period moving average of Sales ## Further Reading - [Pandas MultiIndex Documentation](https://pandas.pydata.org/docs/user_guide/advanced.html) - [Pandas Categorical Data](https://pandas.pydata.org/docs/user_guide/categorical.html) - [Pandas Performance Tips](https://pandas.pydata.org/docs/user_guide/enhancingperf.html) - [Numba Documentation](https://numba.pydata.org/numba-doc/latest/index.html)