pythonintermediate
Pandas Pivot and Unpivot Reshaping
Reshape DataFrames between wide and long formats using pivot, melt, and stack operations.
pythonPress ⌘/Ctrl + Shift + C to copy
import pandas as pd
# Sample data in long format
long_df = pd.DataFrame({
"date": ["2024-01"] * 3 + ["2024-02"] * 3,
"metric": ["revenue", "orders", "users"] * 2,
"value": [10000, 150, 500, 12000, 180, 600],
})
# Pivot: long -> wide
wide_df = long_df.pivot(index="date", columns="metric", values="value").reset_index()
print("Wide format:")
print(wide_df)
# Melt: wide -> long (unpivot)
melted = wide_df.melt(
id_vars=["date"],
value_vars=["orders", "revenue", "users"],
var_name="metric",
value_name="value",
)
print("\nLong format:")
print(melted)
# Pivot table with aggregation
sales = pd.DataFrame({
"region": ["US", "US", "EU", "EU", "US", "EU"],
"product": ["A", "B", "A", "B", "A", "A"],
"amount": [100, 200, 150, 300, 120, 180],
})
pivot_table = pd.pivot_table(
sales, values="amount", index="region", columns="product",
aggfunc=["sum", "count"], fill_value=0, margins=True,
)
print("\nPivot table:")
print(pivot_table)
# Stack / Unstack
stacked = wide_df.set_index("date").stack()
unstacked = stacked.unstack()Use Cases
- Reshaping data for reporting dashboards
- Converting between database and spreadsheet formats
- Preparing data for visualization libraries
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
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
pythonintermediate
Pandas SwapLevel MultiIndex
Swap and sort MultiIndex levels in a hierarchical DataFrame for flexible aggregation.
Best for: hierarchical reporting
#pandas#multiindex