pythonintermediate
Pandas SwapLevel MultiIndex
Swap and sort MultiIndex levels in a hierarchical DataFrame for flexible aggregation.
pythonPress ⌘/Ctrl + Shift + C to copy
import pandas as pd
arrays = [['A','A','B','B'],['x','y','x','y']]
idx = pd.MultiIndex.from_arrays(arrays, names=['group','sub'])
df = pd.DataFrame({'val':[10,20,30,40]}, index=idx)
# Swap levels so sub is first
swapped = df.swaplevel().sort_index()
print(swapped)
print(swapped.loc['x'])Use Cases
- hierarchical reporting
- flexible aggregation
- panel data
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Pandas MultiIndex Stack & Unstack
Work with hierarchical MultiIndex DataFrames: pivoting with stack/unstack and cross-sectional slicing.
Best for: panel data
#pandas#multiindex
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
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
pythonbeginner
Pandas DataFrame Transformations
Common pandas DataFrame transformations including column operations, type casting, and string methods.
Best for: Cleaning raw data files for analysis
#pandas#dataframe