pythonintermediate

Pandas Pivot and Unpivot Reshaping

Reshape DataFrames between wide and long formats using pivot, melt, and stack operations.

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