Sub topic 5
Going back and forth: melt and pivot as inverses
This chapter assumes you know what melt and pivot do on their own. Here you will check that they undo each other. You will also see which details change along the way: column order, row order, and the index.
The idea
melt turns columns into rows. pivot turns rows into columns. When the data has no duplicate key pairs, each call reverses the other. The values survive the trip. The layout details do not always match the original.
Wide to long and back
Start with the wide table and melt it.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B"],
"jan": [100, 80],
"feb": [110, 90],
})
long = wide.melt(id_vars="store", var_name="month", value_name="sales")
print(long)The result has four rows. melt stacks the jan column first, then feb.
store month sales
0 A jan 100
1 B jan 80
2 A feb 110
3 B feb 90Now reverse it with pivot.
back = long.pivot(index="store", columns="month", values="sales")
back = back.reset_index()
back.columns.name = None
print(back) store feb jan
0 A 110 100
1 B 90 80The numbers match the original, but two things changed:
pivotsorts the new columns, sofebcomes beforejan.storebecame the index.reset_index()turns it back into an ordinary column.- The columns carried the name
month. Settingback.columns.name = Noneremoves that label.
Restoring the original layout
To get exactly the table you started with, put the columns back in their original order. Then check the result with pandas' own comparison helper.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B"],
"jan": [100, 80],
"feb": [110, 90],
})
long = wide.melt(id_vars="store", var_name="month", value_name="sales")
back = long.pivot(index="store", columns="month", values="sales")
back = back.reset_index()
back.columns.name = None
back = back[["store", "jan", "feb"]]
pd.testing.assert_frame_equal(back, wide)
print("round trip ok")assert_frame_equal raises an error if values, dtypes, column order, or index differ. It is a quick way to test a reshape.
What can break the round trip
| Difference | Cause | Fix |
|---|---|---|
| Columns in a different order | `pivot` sorts column labels | Select columns in the order you want |
| `store` is the index | `pivot` moves `index=` into the row labels | `reset_index()` |
| Leftover column name `month` | `pivot` names the column axis | `back.columns.name = None` |
| Rows in a different order | `melt` stacks one column at a time | `sort_values` on the key columns, then `reset_index(drop=True)` |
| Error on pivot | Duplicate `store` and `month` pairs | Use `pivot_table` (next chapters) |
The reverse direction has the same limits. If you pivot a long table and melt it again, the rows come out grouped by month rather than by store. Sort both tables on the same keys before comparing them.
Exercise
Exercise
You melt a wide table with columns store, jan and feb, then call long.pivot(index="store", columns="month", values="sales").reset_index(). The result has columns store, feb, jan, and its columns axis is still named "month". Which two steps make it identical to the original wide table?
Show answer
Set back.columns.name = None to remove the leftover "month" label, and reorder the columns with back[["store", "jan", "feb"]] to restore the original order. pivot sorted the month labels alphabetically, which is why feb came before jan.