Sub topic 5
Going back and forth: melt and pivot as inverses
This chapter assumes you can build a DataFrame and select columns. It also assumes you have seen melt turn columns into rows and pivot turn rows into columns. Here you will chain the two calls, see what each round trip changes, and learn how to check that you got your original table back.
The idea: two calls, opposite directions
melt takes a wide table and stacks selected columns into two columns: one for the old column names and one for the values. pivot reverses that. It takes the distinct values of one column and spreads them into new column headers, filling the cells from a values column.
The three arguments of pivot line up with the three roles in a long table:
| Long table role | `melt` argument | `pivot` argument |
|---|---|---|
| Column that identifies the row (store) | `id_vars` | `index` |
| Column holding the old headers (month) | `var_name` | `columns` |
| Column holding the cell values (sales) | `value_name` | `values` |
If you name the same three columns on both sides, the two calls describe the same layout from opposite ends. That is why they behave as inverses.
A first round trip
Start with a small 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) store month sales
0 A jan 100
1 B jan 80
2 A feb 110
3 B feb 90Now pivot it back, using the same three names.
back = long.pivot(index="store", columns="month", values="sales")
print(back)month feb jan
store
A 110 100
B 90 80The numbers are all there, but the result is not identical to wide. Four things differ:
storeis now the row index, not an ordinary column.- The column headers are sorted alphabetically (
feb,jan), not in the original order (jan,feb). - The header axis carries a name,
month, which prints above the index. - The index is named
storeinstead of being a plain 0, 1 range.
Each difference has a one-line fix.
back = (
long.pivot(index="store", columns="month", values="sales")
.reset_index()
.rename_axis(columns=None)
)
print(back) store feb jan
0 A 110 100
1 B 90 80reset_index() turns store back into a column and restores a 0, 1 index. rename_axis(columns=None) removes the month label from the header axis. The column order is still feb, jan. pivot always sorts the new columns, so you must reorder them yourself if order matters.
Checking that you really got the original back
Printing two tables and comparing them by eye misses dtype and label differences. Use the pandas testing helper instead. It raises an AssertionError that describes the first mismatch.
from pandas.testing import assert_frame_equal
restored = (
long.pivot(index="store", columns="month", values="sales")
.reset_index()
.rename_axis(columns=None)[list(wide.columns)]
)
assert_frame_equal(restored, wide)
print("wide -> long -> wide restored the original table")The final [list(wide.columns)] selection puts the columns back in their original order. The assertion passes because the values are integers with no gaps, so pivot keeps int64. The check is worth keeping in a test suite whenever a pipeline reshapes in both directions.
The other direction: long to wide to long
Starting from a long table and returning to it is harder, because melt writes rows in a different order than the one you began with. melt emits all rows for the first value column, then all rows for the second, and so on. Your original long table was probably ordered by store, then month.
long_a = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "feb", "jan", "feb"],
"sales": [100, 110, 80, 90],
})
wide_a = long_a.pivot(index="store", columns="month", values="sales")
long_b = (
wide_a.reset_index()
.melt(id_vars="store", var_name="month", value_name="sales")
.sort_values(["store", "month"], ignore_index=True)
)
expected = long_a.sort_values(["store", "month"], ignore_index=True)
assert_frame_equal(long_b, expected)
print(long_b) store month sales
0 A feb 110
1 A jan 100
2 B feb 90
3 B jan 80Both sides are sorted on the key columns before comparing, because row order in a long table usually carries no meaning. Sorting by the keys gives the comparison a stable order. ignore_index=True renumbers the rows so the leftover index labels do not cause a mismatch.
The sort places feb before jan because the strings sort alphabetically. If your months need calendar order, convert month to an ordered categorical before sorting.
What the round trip does not preserve
The round trip is exact only when your data meets some conditions. Check these before relying on it.
| Situation | What happens | What to do |
|---|---|---|
| Two rows share the same index and columns pair | `pivot` raises a `ValueError` | Aggregate first, or use `pivot_table` (next chapter) |
| A key combination is missing from the long table | `pivot` inserts `NaN`, and integer columns become floats | Drop the `NaN` rows after melting, then restore the dtype |
| The wide table had columns in a meaningful order | `pivot` sorts them | Reorder with a list selection or `reindex` |
| The original had a non-default index | `melt` discards it unless you move it into a column first | Call `reset_index()` before `melt` |
| Value columns have mixed dtypes | `melt` stacks them into one column, which becomes `object` | Melt same-typed columns together, or convert after |
Missing combinations
Suppose store B has no February record at all. The long table is shorter, and pivot has to invent a cell.
partial = pd.DataFrame({
"store": ["A", "A", "B"],
"month": ["jan", "feb", "jan"],
"sales": [100, 110, 80],
})
wide_p = partial.pivot(index="store", columns="month", values="sales")
print(wide_p)month feb jan
store
A 110.0 100.0
B NaN 80.0Two changes happened. The missing cell is NaN, and the whole column became float64 because plain integers cannot hold NaN. Melting back now yields four rows, one of them empty. To recover the original three rows you must remove the empty one and cast the dtype back.
recovered = (
wide_p.reset_index()
.melt(id_vars="store", var_name="month", value_name="sales")
.dropna(subset=["sales"])
.astype({"sales": "int64"})
.sort_values(["store", "month"], ignore_index=True)
)
print(recovered) store month sales
0 A feb 110
1 A jan 100
2 B jan 80This loses nothing as long as NaN never appears as a genuine value in the original. If the original long table contained real NaN sales values, dropna would remove them, and the round trip would no longer be exact. In that case, keep a separate record of which rows were present.
Several identifier columns
When rows are identified by more than one column, pass a list on both sides. For example, if each row is keyed by store and region, use id_vars=["store", "region"] for melt and index=["store", "region"] for pivot. The list order sets the order of the resulting index levels. After reset_index(), both columns return as ordinary columns. A key that is missing from the index list ends up merged with other rows, which then triggers duplicate errors, so list every identifying column.
A reusable pattern
When you need the same round trip several times, wrap the cleanup steps in small functions so each call site stays short.
def to_long(df, id_col, var_name, value_name):
return df.melt(id_vars=id_col, var_name=var_name, value_name=value_name)
def to_wide(df, id_col, var_name, value_name, column_order=None):
out = (
df.pivot(index=id_col, columns=var_name, values=value_name)
.reset_index()
.rename_axis(columns=None)
)
if column_order is not None:
out = out[[id_col, *column_order]]
return out
long_c = to_long(wide, "store", "month", "sales")
wide_c = to_wide(long_c, "store", "month", "sales", column_order=["jan", "feb"])
assert_frame_equal(wide_c, wide)
print(wide_c) store jan feb
0 A 100 110
1 B 80 90The helpers handle one identifier column only. Extend them with a list if your tables need more.
Summary of the working rules
- Name the same three roles on both sides: identifier, old header, value.
- After
pivot, callreset_index()andrename_axis(columns=None)to get an ordinary table. pivotsorts the new columns. Reorder them yourself if the order matters.- After
melt, sort on the key columns before comparing, and useignore_index=True. - Verify with
assert_frame_equal, not by eye. - Expect
NaNand float dtypes whenever a key combination is absent, and expect aValueErrorwhenever one is repeated.
Exercise
You melt a wide table with id_vars="store", then pivot the result with index="store", columns="month", values="sales". The table you get back has the right numbers, but assert_frame_equal(back, wide) fails. List three differences you would check first, and give the calls that fix them.
Show answer
First, store is the index after pivot, so call reset_index(). Second, the header axis still carries the name month, so call rename_axis(columns=None). Third, pivot sorts the new columns alphabetically, so reorder them with back[list(wide.columns)]. Row labels should then be 0, 1, ... again, and with integer data and no missing keys the dtypes also match.
Exercise
A long table has rows (A, jan, 100), (A, feb, 110) and (B, jan, 80). You run pivot(index="store", columns="month", values="sales"). What is the dtype of the feb column, and why? How do you get back exactly the original three rows after melting?
Show answer
The feb column is float64. Store B has no February row, so pivot fills that cell with NaN, and integers cannot hold NaN. After reset_index() and melt, drop the empty row with dropna(subset=["sales"]), cast with astype({"sales": "int64"}), and sort on ["store", "month"] with ignore_index=True. This only works if the source had no genuine NaN sales values.