A pandas pivot table turns a long list of records into a grid you can read at a glance, and melt turns the grid back into a list. This guide runs each function on a real dataset, the 144-row monthly airline passenger series that ships with seaborn, and then shows the one mistake that quietly gives wrong numbers: pivoting data that has duplicate rows.
Everything below was run with pandas 3.0.5, and the outputs are pasted exactly as printed. If you are new to grouping, read Pandas GroupBy Explained first, because pivot_table is a groupby with a nicer layout.
Long data and wide data
Long data has one row per observation. Wide data has one row per entity and one column per category. The airline file is long: one row per month.
import pandas as pd
df = pd.read_csv("flights.csv") # seaborn-data flights.csv
print(df.head(3))
print(df.shape)Output:
year month passengers
0 1949 January 112
1 1949 February 118
2 1949 March 132
(144, 3)pivot: reshape without aggregating
pivot moves values into a grid and does no arithmetic. Each (year, month) pair must appear exactly once.
wide = df.pivot(index="year", columns="month", values="passengers")
print(wide.iloc[:3, :5])
print(wide.shape)Output:
month April August December February January
year
1949 129 148 118 118 112
1950 135 170 140 126 115
1951 163 199 166 150 145
(12, 12)Notice the column order: April, August, December. Pandas sorted the month names alphabetically, which is rarely what you want. Reindex the columns with an explicit list:
order = ["January","February","March","April","May","June","July",
"August","September","October","November","December"]
wide = wide[order]
print(wide.iloc[:3, :5])Output:
month January February March April May
year
1949 112 118 132 129 121
1950 115 126 141 135 125
1951 145 150 178 163 172Pandas pivot table: reshape and aggregate
When rows can repeat, or you want totals, use pivot_table. It takes an aggfunc and can add row and column totals with margins. Here we group months into quarters first.
df["quarter"] = "Q" + (df["month"].map(order.index) // 3 + 1).astype(str)
pt = df.pivot_table(index="year", columns="quarter", values="passengers",
aggfunc="sum", margins=True, margins_name="Total")
print(pt.loc[[1949, 1950, 1960, "Total"]])Output:
quarter Q1 Q2 Q3 Q4 Total
year
1949 362 385 432 341 1520
1950 382 409 498 387 1676
1960 1227 1468 1736 1283 5714
Total 8963 10207 12058 9135 40363Total traffic grew 3.76 times between 1949 (1,520) and 1960 (5,714), and the third quarter is the busiest in every year shown. Averaging by month gives the seasonal pattern in the chart below: July and August average 351 against 232.8 for November, so July runs about 1.51 times November (the unit is thousands of passengers, as in the original Box and Jenkins series).

The duplicate trap: pivot versus pivot_table
This is the part that surprises people. Add one duplicated row to the data and the two functions behave very differently.
d2 = pd.concat([df, df.iloc[[0]]])
try:
d2.pivot(index="year", columns="month", values="passengers")
except ValueError as e:
print("pivot error:", e)
# a duplicate that disagrees: 212 vs 112 for January 1949
d3 = pd.concat([df.assign(passengers=df.passengers.where(df.index != 0, 212)),
df.iloc[[0]]])
print(d3.pivot_table(index="year", columns="month", values="passengers")
.loc[1949, "January"])Output:
pivot error: Index contains duplicate entries, cannot reshape
162.0pivot refuses to guess and raises an error, which is the safe behaviour. pivot_table silently averaged the conflicting values (212 and 112) into 162, a number that appears nowhere in the source. When your key should be unique, check it first with df.duplicated(["year","month"]).any() or use pivot so bad data fails loudly. Our pandas merge and join guide covers the same habit for joins, and cleaning data with Python shows how to remove duplicates.
melt: wide back to long
melt is the inverse. Plotting libraries and groupby usually want long data.
long = wide.reset_index().melt(id_vars="year", var_name="month",
value_name="passengers")
chk = long.merge(df, on=["year", "month"], suffixes=("", "_o"))
print(long.shape, (chk.passengers == chk.passengers_o).all())
s = wide.stack() # Series with a (year, month) MultiIndex
print(type(s).__name__, s.shape, s.loc[(1949, "January")], s.unstack().equals(wide))Output:
(144, 3) True
Series (144,) 112 TrueThe round trip returns all 144 rows with identical values. stack and unstack do the same job on the index instead of columns, which is handy when your data already has a MultiIndex.
crosstab: counts and rates for categories
For two categorical columns, pd.crosstab is shorter than a pivot table. Using the seaborn Titanic data (891 passengers):
t = pd.read_csv("titanic.csv")
print(pd.crosstab(t["class"], t["sex"], values=t["survived"], aggfunc="mean").round(3))
print(pd.crosstab(t["class"], t["survived"], margins=True))Output:
sex female male
class
First 0.968 0.369
Second 0.921 0.157
Third 0.500 0.135
survived 0 1 All
class
First 80 136 216
Second 97 87 184
Third 372 119 491
All 549 342 891Survival depended on both sex and class: 96.8% of first-class women survived against 13.5% of third-class men. Those are survival shares in this file, not a causal effect; our piece on correlation vs causation explains why that distinction matters.
Which function should you use?
Use pivot for a pure reshape when the key is unique, pivot_table when you need an aggregate or totals, melt to go back to long, and crosstab for quick category counts. The official reference is the pandas reshaping user guide. For a one-page list of related commands, see the pandas cheat sheet.
Frequently asked questions
What is the difference between pivot and pivot_table in pandas?
pivot only reshapes and raises an error if a (row, column) pair repeats. pivot_table aggregates repeated pairs with aggfunc (mean by default), so it never fails on duplicates but can hide them.
How do I keep month names in calendar order?
Pandas sorts labels alphabetically. Select the columns with an explicit list, as above, or convert the column to an ordered categorical.
How do I add totals to a pandas pivot table?
Pass margins=True and, if you like, margins_name="Total".
When should I use melt?
Use it when a table has one column per period or category and you need one row per observation, for example before plotting or grouping.
Data note: the flights series is a classic teaching dataset, so treat the numbers as an illustration of the methods, not current airline traffic.
