Alt+←/→to navigatePage9/1464
Pivoting & Reshaping Data · Page 1 of 1
Pivot Tables
15 min Intermediate
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…