TExcelTAD
Home › pandas › Reshaping with melt(), stack() and unstack()

Reshaping with melt(), stack() and unstack()

The same data can be laid out wide (one column per variable or per period) or long (one row per observation). Spreadsheets and reports usually prefer wide; analysis and plotting tools usually prefer long, also called tidy data. pandas converts between the two:

Direction Tools
wide → long melt(), stack()
long → wide pivot(), pivot_table(), unstack()

melt(): wide to long

Here's how a teacher might keep grades in a spreadsheet, one column per term:

python · try it yourself
import pandas as pd

wide = pd.DataFrame({
    "student": ["Ines", "Jamal", "Keiko"],
    "term1": [72, 85, 90],
    "term2": [78, 81, 94],
    "term3": [84, 88, 91],
})
long = wide.melt(id_vars="student", var_name="term", value_name="grade")
print(long)
  student   term  grade
0    Ines  term1     72
1   Jamal  term1     85
2   Keiko  term1     90
3    Ines  term2     78
4   Jamal  term2     81
5   Keiko  term2     94
6    Ines  term3     84
7   Jamal  term3     88
8   Keiko  term3     91

id_vars are the columns that identify a row and stay as they are. Every other column is "melted": its name goes into the new term column and its value into grade. Three students × three terms = nine rows.

Long data makes group calculations easy:

python · try it yourself
import pandas as pd

wide = pd.DataFrame({
    "student": ["Ines", "Jamal", "Keiko"],
    "term1": [72, 85, 90],
    "term2": [78, 81, 94],
    "term3": [84, 88, 91],
})
long = wide.melt(id_vars="student", var_name="term", value_name="grade")
print(long.groupby("term")["grade"].mean().round(1))
print(long.loc[long.groupby("student")["grade"].idxmax()])
term
term1    82.3
term2    84.3
term3    87.7
Name: grade, dtype: float64
  student   term  grade
6    Ines  term3     84
7   Jamal  term3     88
5   Keiko  term2     94

The second line finds each student's best term, something awkward to do in the wide layout.

Choosing which columns to melt

value_vars limits the melt to some columns. Columns that are neither id_vars nor value_vars are dropped:

python · try it yourself
import pandas as pd

wide = pd.DataFrame({
    "student": ["Ines", "Jamal"],
    "class": ["7B", "7A"],
    "term1": [72, 85],
    "term2": [78, 81],
    "term3": [84, 88],
})
print(wide.melt(id_vars=["student", "class"], value_vars=["term1", "term3"],
                var_name="term", value_name="grade"))
  student class   term  grade
0    Ines    7B  term1     72
1   Jamal    7A  term1     85
2    Ines    7B  term3     84
3   Jamal    7A  term3     88

Back to wide with pivot()

pivot() is the reverse of melt():

python · try it yourself
import pandas as pd

long = pd.DataFrame({
    "student": ["Ines", "Ines", "Jamal", "Jamal"],
    "term": ["term1", "term2", "term1", "term2"],
    "grade": [72, 78, 85, 81],
})
wide = long.pivot(index="student", columns="term", values="grade")
print(wide)
print(wide.reset_index().rename_axis(columns=None))
term     term1  term2
student
Ines        72     78
Jamal       85     81
  student  term1  term2
0    Ines     72     78
1   Jamal     85     81

reset_index() turns student back into a column, and rename_axis(columns=None) removes the leftover term label above the columns.

stack() and unstack()

stack() and unstack() move labels between the column axis and the row index. unstack() takes the innermost row-index level and spreads it into columns; stack() does the opposite:

python · try it yourself
import pandas as pd

visits = pd.DataFrame({
    "site": ["blog", "blog", "shop", "shop"],
    "device": ["mobile", "desktop", "mobile", "desktop"],
    "visits": [1200, 800, 950, 1430],
}).set_index(["site", "device"])["visits"]

print(visits)
table = visits.unstack()
print(table)
print(table.stack())
site  device
blog  mobile     1200
      desktop     800
shop  mobile      950
      desktop    1430
Name: visits, dtype: int64
device  desktop  mobile
site
blog        800    1200
shop       1430     950
site  device
blog  desktop     800
      mobile     1200
shop  desktop    1430
      mobile      950
dtype: int64

unstack() is especially handy right after a two-key groupby, turning the result into a readable grid:

python · try it yourself
import pandas as pd

trips = pd.DataFrame({
    "mode": ["bus", "bike", "bus", "car", "bike", "car", "bus"],
    "weekday": ["Mon", "Mon", "Tue", "Tue", "Tue", "Mon", "Mon"],
    "km": [12, 5, 14, 30, 6, 28, 11],
})
print(trips.groupby(["mode", "weekday"])["km"].sum().unstack(fill_value=0))
weekday  Mon  Tue
mode
bike       5    6
bus       23   14
car       28   30

Tip: If you're unsure which layout you need, aim for long: one row per observation, one column per variable. It's easy to pivot to wide at the end for presentation.

Test yourself

A table has columns city, 2022, 2023, 2024. Which call turns it into rows of (city, year, value)?

  1. df.pivot(index="city")
  2. df.melt(id_vars="city", var_name="year")
  3. df.stack("city")
  4. df.groupby("city").sum()

What is the reverse of melt()?

  1. concat()
  2. pivot()
  3. merge()
  4. explode()

What does unstack() do with a Series that has a two-level index?

  1. Sorts it
  2. Moves the inner index level into columns
  3. Removes the index
  4. Melts it