Reshaping: melt and pivot
melt turns wide data into long data. pivot_table turns long data back into a wide summary.
Wide to long with melt
This frame has one column per month. melt turns the month columns into rows.
import pandas as pd
df = pd.DataFrame({
"product": ["Tea", "Coffee"],
"Jan": [2, 1],
"Feb": [4, 3],
})
print(df.melt(id_vars="product", var_name="month", value_name="units"))Long to wide with pivot_table
pivot_table turns the month rows back into columns. Each product gets one row.
import pandas as pd
df = pd.DataFrame({
"product": ["Tea", "Tea", "Coffee", "Coffee"],
"month": ["Jan", "Feb", "Jan", "Feb"],
"units": [2, 4, 1, 3],
})
print(df.pivot_table(index="product", columns="month", values="units"))Add up instead of averaging
aggfunc="sum" adds the values in each cell instead of averaging them. Tea in January has two rows, so the cell holds 6.
import pandas as pd
df = pd.DataFrame({
"product": ["Tea", "Tea", "Coffee"],
"month": ["Jan", "Jan", "Jan"],
"units": [2, 4, 1],
})
print(df.pivot_table(index="product", columns="month", values="units", aggfunc="sum"))Example
import io
import pandas as pd
SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""
sales = pd.read_csv(io.StringIO(SALES_CSV))
print(sales.pivot_table(index="category", columns="region", values="units", aggfunc="sum"))Key points
- Wide data keeps one column per value, like one column per month.
- Long data keeps one row per value, like one row per month.
- Use melt to turn columns into rows.
- Pass id_vars to melt to name the columns that stay put.
- Use pivot_table to turn rows back into columns.
- pivot_table gathers rows by the index column and combines the values in each cell.
In this example, the sales table loads from the CSV text. pivot_table gathers the rows by category and region. aggfunc="sum" adds the units in each cell. Office in the North sold 5 units, the largest cell in the table.
Note
Two rows for the same cell are combined into one value. The default combination is the average.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which call turns one column per month into one row per month?