Page14/14
Advanced Data Transformations Β· Page 1 of 1
Melt, Stack, & MultiIndex
Advanced Data Transformations
Melt β Wide to Long Format
Transform columns into rows. Perfect for preparing data for plotting or modeling.
# Wide format: each category is a column
data_wide = {
"city": ["NYC", "LA", "Chicago"],
"2020": [100, 150, 200],
"2021": [120, 160, 220],
"2022": [140, 180, 250]
}
df_wide = pd.DataFrame(data_wide)
# Melt to long format
df_long = df_wide.melt(id_vars="city", var_name="year", value_name="sales")
Result: Each row represents one (city, year) pair.
Stack & Unstack
- Stack: Pivot rows β columns (opposite of melt)
- Unstack: Pivot index levels β columns
df.set_index(['region', 'product']).unstack()
MultiIndex (Hierarchical Index)
Index with multiple levels for organizing complex data:
df = pd.DataFrame({
'value': range(6)
}, index=pd.MultiIndex.from_tuples([
('A', 'X'), ('A', 'Y'), ('B', 'X'),
('B', 'Y'), ('C', 'X'), ('C', 'Y')
], names=['region', 'product']))
df.loc['A'] # Get all products in region A
df.loc['A', 'X'] # Get specific region-product
When to use: MultiIndex is powerful but can be confusing. Use it when you have hierarchical data (years > months > days).
main.py
Loading...
OUTPUT
βΆClick "Run Code" to executeβ¦