pandas in depth · lesson 4 of 12
Parts in this lesson
Adf.pivot(index=, columns=, values=)long to wide
Bwide.melt(id_vars="date")wide to long
Cpivot_table(..., aggfunc="sum")wide, adding up repeats
Dpd.crosstab(a, b)count each pair

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 pivot and pivot_table, and a long one with melt
  • Move an index level into the columns and back with unstack and stack
  • Explain why pivot fails on repeated entries, and use pivot_table instead

Long and wide

Step through the same six numbers in both shapes, then run the cells.

A long table pivoted wide, and melted back. Long: one row per store per day, and one column for kilos. Easy to filter, group and add rows to.01-02Batangas4201-02Lipa3501-02Tanauan2901-03Batangas3801-03Lipa3301-03Tanauan30longdatestorekilos
1 of 3 Long: one row per store per day, and one column for kilos. Easy to filter, group and add rows to.
shapes.ipynb
  • 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.
  • melt goes back to long. id_vars are the columns to keep as they are; every other column's name goes into a new store column (var_name) and its values into kilos (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's groupby(["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.

stack.ipynb

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.

pivot.ipynb

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

You’ll group, filter and chart sales by store and month. Which shape should the table be?
A wide table has columns store, Jan, Feb, Mar. What makes it long?
pivot fails with “duplicate entries”. What does that tell you?

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.

All sources for Simple Data Analysis