Reshape between wide and long tables

3.1.1

Move repeated measurement columns into rows and choose how to pivot them back.

On this page

Move measurement columns into rows

Wide data can store one column per month. melt keeps the identifier columns and puts the former column names and their values into two columns. The row grain changes from one row per store to one row per store and month.

import pandas as pd

wide = pd.DataFrame({"store": ["A", "B"], "Jan": [8, 6], "Feb": [10, 9]})
long = wide.melt(id_vars="store", var_name="month", value_name="units")
for row in long.itertuples(index=False):
    print(row.store, row.month, row.units)
The wide table has one row per store. The long table has four rows, one for each store and month pair. Download image
The value 10 moves from store A’s Feb column to a row labeled A and Feb.
Example output
A Jan 8
B Jan 6
A Feb 10
B Feb 9

Pivot unique pairs or aggregate repeats

pivot requires each index and column pair to be unique. If multiple rows for one store and month represent separate orders, use pivot_table with a deliberate aggregation. Verify the row grain before deciding whether summing is meaningful.

import pandas as pd

orders = pd.DataFrame({
    "store": ["A", "A", "A"],
    "month": ["Jan", "Jan", "Feb"],
    "units": [3, 5, 10],
})
summary = orders.pivot_table(index="store", columns="month", values="units", aggfunc="sum")
print(summary.loc["A", ["Jan", "Feb"]].tolist())
Example output
[8, 10]

Official references