Reshaping: long and wide
Last updated
The same numbers can be laid out two ways: long, with one row per store per day, or wide, with a column for each store. Long is easier to analyse; wide is easier to read. In this lesson you'll turn tables from one shape to the other with pivot, melt, stack and unstack, build a summary table with pivot_table, and count pairs with crosstab.
By the end of this lesson you can
- Tell a long table from a wide one, and say what each is good for
- Make a wide table with
pivotandpivot_table, and a long one withmelt - Move an index level into the columns and back with
unstackandstack - Explain why
pivotfails on repeated entries, and usepivot_tableinstead
Long and wide
Step through the same six numbers in both shapes, then run the cells.
pivot(index="date", columns="store", values="kilos"): one row per date, one column per store. Each pair of date and store must appear only once.meltgoes back to long.id_varsare the columns to keep as they are; every other column's name goes into a newstorecolumn (var_name) and its values intokilos(value_name).reset_index()first, because the dates were the index.
Which to use? Long for analysis: groupby, filters, joins and the chart libraries in Stages 6 and 7 all expect it. Wide for showing people: a table in a report, or the spreadsheet someone asked for. Analyse long; pivot at the end.
Summary tables
The last two cells above, and a new notebook:
pivot_table(index="store", columns="item", values="kilos", aggfunc="sum")is a spreadsheet pivot table: stores down, items across, kilos added up. It'sgroupby(["store", "item"]).sum()laid out wide.pd.crosstab(a, b)counts how many rows have each pair. Every store has 2 rows of rice and 2 of sugar.
unstack and stack do the same for an index. Run them.
unstack() moves the inner index level (item) into the columns: the same table as pivot_table. stack() moves it back. You'll use unstack() most, straight after a groupby with two keys.
Wrong way: pivot with repeats
You want dates down and stores across, from the full sales table. Run it.
Index contains duplicate entries, cannot reshape. Each store has two rows per date, rice and sugar, and pivot has one cell for each date and store. It won't choose between 42 and 12, and it won't add them up without being told.
Two fixes, depending on what you meant:
- If the repeats should be combined, say how:
pivot_table(..., aggfunc="sum"). - If they shouldn't exist at all, the error has found a problem in your data. Find the repeats with
df.duplicated(["date", "store"], keep=False)before you choose.
pivot_table never fails this way, which is also its risk: with aggfunc="mean" (its default) it will quietly average rows that were really duplicates. Know which one you have.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- pandas: Reshaping and pivot tables: pivot, pivot_table, melt, stack, unstack and crosstab
- pandas: pandas.DataFrame.pivot_table: aggfunc, margins and fill_value
- Wickham, Tidy Data, Journal of Statistical Software 59(10), 2014: why long tables are easier to analyse