pythonintermediate

Pandas MultiIndex Stack & Unstack

Work with hierarchical MultiIndex DataFrames: pivoting with stack/unstack and cross-sectional slicing.

python
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.