pythonintermediate
Pandas MultiIndex Stack & Unstack
Work with hierarchical MultiIndex DataFrames: pivoting with stack/unstack and cross-sectional slicing.
pythonPress ⌘/Ctrl + Shift + C to copy
import pandas as pd
arrays = [['A', 'A', 'B', 'B'], ['x', 'y', 'x', 'y']]
index = pd.MultiIndex.from_arrays(arrays, names=['group', 'subgroup'])
df = pd.DataFrame({'val': [10, 20, 30, 40], 'cnt': [1, 2, 3, 4]}, index=index)
pivoted = df['val'].unstack('subgroup')
print(pivoted)
print(df.xs('A', level='group'))
print(df.reset_index())Use Cases
- panel data
- cross-sectional analysis
- pivot reporting
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Pandas Pivot and Unpivot Reshaping
Reshape DataFrames between wide and long formats using pivot, melt, and stack operations.
Best for: Reshaping data for reporting dashboards
#pandas#pivot
pythonintermediate
Pandas SwapLevel MultiIndex
Swap and sort MultiIndex levels in a hierarchical DataFrame for flexible aggregation.
Best for: hierarchical reporting
#pandas#multiindex
pythonbeginner
Pandas Wide to Long (melt)
Transform a wide-format DataFrame into long format using pd.melt for analytics and visualisation.
Best for: pivot table conversion
#pandas#melt
pythonintermediate
Polars Pivot and Unpivot
Reshape a Polars DataFrame from long to wide (pivot) and wide to long (unpivot/melt).
Best for: data reshaping
#polars#pivot