9/14
Pivoting & Reshaping Data Β· Page 1 of 1

Pivot Tables

Pivoting & Reshaping Data

What is a Pivot Table?

A pivot table reorganizes data β€” rotating rows into columns or vice versa. It's the Excel pivot table but in code.

Reshape with pivot_table()

import pandas as pd

# Long format (tidy data)
df = pd.DataFrame({
    "date": ["2024-01", "2024-01", "2024-02", "2024-02"],
    "region": ["North", "South", "North", "South"],
    "sales": [100, 150, 120, 180]
})

# Pivot to wide format
pivot = df.pivot_table(
    values="sales",
    index="date",
    columns="region",
    aggfunc="sum"
)

Multiple Aggregations

pivot = df.pivot_table(
    values="sales",
    index="region",
    aggfunc=["sum", "mean", "count"]
)
main.py
Loading...
OUTPUT
β–ΆClick "Run Code" to execute…