ZetCode

Pandas Reshaping: melt and pivot

last modified November 17, 2026 Python 3.15

The same data can be laid out in two quite different ways. In wide form each variable gets its own column, so one row holds many related measurements. In long form each observation gets its own row, with one column naming the variable and another holding its value. Reshaping means converting between these layouts, and Pandas provides melt, pivot, stack, unstack and wide_to_long for the job.

All examples were verified with pandas 3.1.1 and build their own small DataFrame so they can be run independently.

Wide versus long form

Let us start with a table in wide form. It lists two students and two exam scores; the scores sit in separate math and english columns. This layout is pleasant to read, but awkward when we want to treat "exam" as a single variable — for example to filter or group by it.

reshape_wide.py
import pandas as pd

wide = pd.DataFrame({
    'name': ['Alice', 'Bob'],
    'math': [90, 80],
    'english': [85, 95]
})
print(wide)

There are two rows, one per student, and the two score columns hold the measurements. In long form the same information would occupy four rows, each combining a student, a subject name and a score. The next section performs that conversion.

$ python reshape_wide.py
    name  math  english
0  Alice    90       85
1    Bob    80       95

Melting to long form

The melt method turns wide data into long data. Its id_vars argument names the columns that should stay put as identifiers, here name. The value_vars argument lists the columns to fold into two new ones. By default those new columns are called variable and value, but var_name and value_name let us choose clearer names, subject and score.

reshape_melt.py
import pandas as pd

wide = pd.DataFrame({
    'name': ['Alice', 'Bob'],
    'math': [90, 80],
    'english': [85, 95]
})
long = wide.melt(id_vars='name', value_vars=['math', 'english'],
                 var_name='subject', value_name='score')
print(long)

Each original score becomes its own row. There are two students and two subjects, so the result has four rows. The name value is repeated for the two subjects belonging to a student, while subject holds the former column name and score holds the number that was in the cell. Long form is the shape most Pandas grouping and plotting operations prefer.

$ python reshape_melt.py
    name  subject  score
0  Alice     math     90
1    Bob     math     80
2  Alice  english     85
3    Bob  english     95

Pivoting back to wide form

The pivot method is the inverse of melt. Its index argument names the column whose values become row labels, columns names the column whose values become column labels, and values names the column that supplies the cell contents. Each row-and-column pair must be unique, otherwise Pandas raises an error; when there are duplicates, use pivot_table instead, as described in Pandas pivot tables.

reshape_pivot.py
import pandas as pd

long = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Alice', 'Bob'],
    'subject': ['math', 'math', 'english', 'english'],
    'score': [90, 80, 85, 95]
})
wide = long.pivot(index='name', columns='subject', values='score')
print(wide)

We are back to two rows, with english and math as columns. Notice that the columns appear in alphabetical order, so english comes before math even though the long table listed math first. The row labels are now the index rather than a regular column, which is why the line below them reads name.

$ python reshape_pivot.py
subject  english  math
name                  
Alice         85    90
Bob           95    80

A wide-long-wide round trip

Because melt and pivot are inverses, we can convert a table to long form and straight back again. This round trip is useful when an operation is easier in one shape — for instance, scaling every score in long form — before returning to the original layout. The final lines below restore the column order and the index so the result can be compared with the starting table.

reshape_roundtrip.py
import pandas as pd

wide = pd.DataFrame({
    'name': ['Alice', 'Bob'],
    'math': [90, 80],
    'english': [85, 95]
})
print('wide:')
print(wide)
print()

long = wide.melt(id_vars='name', value_vars=['math', 'english'],
                 var_name='subject', value_name='score')
print('long:')
print(long)
print()

back = long.pivot(index='name', columns='subject', values='score')
back = back[['math', 'english']].rename_axis(None, axis=1).reset_index()
print('wide again:')
print(back)
print()
print('round trip equal:', back.equals(wide))

The three tables are printed in sequence, and the last line confirms that the recovered table equals the original. The helper calls rename_axis removes the name of the column index and reset_index turns name back into an ordinary column. Without them the values would still match, but the layout would differ slightly from where we started.

$ python reshape_roundtrip.py
wide:
    name  math  english
0  Alice    90       85
1    Bob    80       95

long:
    name  subject  score
0  Alice     math     90
1    Bob     math     80
2  Alice  english     85
3    Bob  english     95

wide again:
    name  math  english
0  Alice    90       85
1    Bob    80       95

round trip equal: True

Stack and unstack

The stack and unstack methods reshape data using the index instead of named value columns. stack moves the innermost column level into the index, producing a Series with a MultiIndex — an index that has more than one level. Here we first set name as the index so that the subjects are the columns to be stacked. unstack performs the reverse move.

reshape_stack.py
import pandas as pd

df = pd.DataFrame({
    'name': ['Alice', 'Bob'],
    'math': [90, 80],
    'english': [85, 95]
}).set_index('name')
stacked = df.stack()
print('stacked:')
print(stacked)
print()
print('unstacked:')
print(stacked.unstack())

The stacked result is a Series whose index pairs a student with a subject, so Alice math maps to 90. Calling unstack on it lifts the inner index level back out to become columns, recovering the original table. This pair is most convenient when the categories to reshape are already part of the index.

$ python reshape_stack.py
stacked:
name          
Alice  math       90
       english    85
Bob    math       80
       english    95
dtype: int64

unstacked:
       math  english
name                
Alice    90       85
Bob      80       95

wide_to_long

The wide_to_long function handles a regular family of column names in one step. Its stubnames argument gives the shared prefixes, i names the identifier column, j names the new column that will hold the varying suffix, and suffix is a pattern matching that suffix. Here columns such as math1 and math2 share the stub math and the numeric suffix that becomes the exam number.

reshape_wide_to_long.py
import pandas as pd

df = pd.DataFrame({
    'id': [1, 2],
    'math1': [90, 80],
    'math2': [85, 95],
    'english1': [70, 75],
    'english2': [60, 65]
})
result = pd.wide_to_long(df, stubnames=['math', 'english'],
                         i='id', j='exam', suffix=r'\d+')
print(result)

The result has a MultiIndex made of id and exam, and two columns, math and english. Student 1 sat exam 1 (math 90, english 70) and exam 2 (math 85, english 60). This saves writing a separate melt call for every stub when column names follow a predictable pattern.

$ python reshape_wide_to_long.py
         math  english
id exam               
1  1       90       70
2  1       80       75
1  2       85       60
2  2       95       65

Choosing the right tool

Use melt to fold a few named columns into long form, and pivot to turn unique row-and-column pairs back into a wide table. Choose stack and unstack when the categories are part of the index, and wide_to_long when many column names share a stub and a numbered suffix.

If the same cell can occur more than once, pivot cannot decide which value to keep; reach for pivot_table with an aggregation function instead. That method and its options are covered in Pandas pivot tables.

Source

Pandas DataFrame.melt Documentation, Pandas DataFrame.pivot Documentation, Pandas DataFrame.stack Documentation, and Pandas wide_to_long Documentation

In this article we have compared wide and long form, melted a table to long form, pivoted it back, completed a verified round trip, reshaped with stack and unstack, and used wide_to_long for patterned column names. For summarising while reshaping see Pandas pivot tables, and for grouping rows see the grouping data tutorial.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pandas tutorials.