Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
pandas unstack() pivots a level of a MultiIndex into columns: DataFrame.unstack(level=-1, fill_value=None, sort=True) takes the innermost index level by default and turns its labels into the new innermost level of the column labels, returning a wider table. If the index has only one level, the result is a Series with a MultiIndex instead. It is the inverse of stack(), and it is the usual last step after a groupby that summarises data by two keys (for example participant and condition). This guide also answers the common search “unstack pandas” and uses pandas 3.1.1, the version whose documentation was read for it.
What unstack is used for in research
Research data usually arrive in long form: one row per observation, with a column for the participant, a column for the condition and a column for the measurement. Summaries and figures often need wide form, with one row per participant and one column per condition. groupby([...]).agg(...) returns the summary with a two-level index, and unstack() moves one of those levels across the top. The same call helps when you need a participant-by-condition matrix for a paired test, a table for a manuscript, or a heatmap input.
The pandas documentation describes the method as pivoting a level of the (necessarily hierarchical) index labels. That wording matters: unstack() works on the index, not on ordinary columns. If your keys are still columns, either move them into the index with set_index or use DataFrame.pivot, covered in pandas pivot. For background on why long and wide layouts matter for analysis, see tidy data rules for structuring research data. Readers coming from Stata will recognise the same job in the Stata reshape command.
Install or access pandas
The official installation page lists two routes. With pip: pip install pandas. With conda from conda-forge: conda install -c conda-forge pandas. The page recommends working inside a virtual environment, for example conda create -c conda-forge -n name_of_my_env python pandas followed by conda activate name_of_my_env. Optional extras are installed with pip extras such as pip install "pandas[excel]". The Python versions supported by each release are set out in the pandas Python support policy linked from the installation page. Everything on this page runs with import pandas as pd.
Syntax and arguments
level
level accepts an integer, a level name, or a list of those, and defaults to -1, the last level. Passing a list is the same as unstacking each level in turn, and the list may hold names or numbers but not a mix of the two. stacked.unstack(1) and stacked.unstack("second") give identical output when the second level is named second. Using names is safer in analysis code, because a level number silently changes meaning if someone adds or reorders index levels upstream.
fill_value
fill_value is a scalar that replaces the NaN values the operation produces when some subgroups do not share the same labels. The default is None, which leaves NaN in place. Use it deliberately: a placeholder such as 0 is a statement that the cell was observed as zero, which is not true of a participant who never took part in a condition.
sort
sort is a boolean, default True. It sorts the level or levels in the resulting MultiIndex columns and also orders the rows: by the remaining levels when True, by order of first appearance when False. The user guide also notes that unstack() implicitly sorts the index levels involved, so stacking and then unstacking returns a sorted copy of the original rather than the identical row order.
Return value
The result is a DataFrame when the index is a MultiIndex, with the pivoted index labels as the new innermost level of the column labels. For a single-level index the result is a Series.
Step-by-step: from long data to a participant-by-condition table
The following example uses a small illustrative dataset made up for this page (an illustrative composite, not real study data): three participants, three conditions, one score each, with participant P2 missing the “low” condition. The outputs shown were produced by running the code in pandas 3.1.1.
- Build the long table.
df = pd.DataFrame({"participant": ["P1","P1","P1","P2","P2","P3","P3","P3"], "condition": ["control","low","high","control","high","control","low","high"], "score": [10.0,12.0,15.0,11.0,16.0,9.0,13.0,14.0]}) - Summarise by both keys.
g = df.groupby(["participant","condition"])["score"].mean()returns a Series with a two-level index (participant, condition) holding eight rows. - Unstack the innermost level.
g.unstack()movesconditionacross the columns. - Choose the other level when you want conditions as rows.
g.unstack(level=0)(org.unstack("participant")) puts participants across the top. - Decide what to do with the gap.
g.unstack("condition", fill_value=0)replaces the missing cell with 0; the default leaves NaN. - Return the index to ordinary columns for export.
w = g.unstack(); w.columns.name = None; w.reset_index()gives a flat table with aparticipantcolumn.
Output and how to read it
After g.unstack() the table reads as follows. Columns are sorted alphabetically because sort=True, so “high” comes before “low”.
| participant | control | high | low |
|---|---|---|---|
| P1 | 10.0 | 15.0 | 12.0 |
| P2 | 11.0 | 16.0 | NaN |
| P3 | 9.0 | 14.0 | 13.0 |
The row index is participant and the columns carry the name condition. The NaN for P2 is not an error: the long table had no row for P2 under “low”, so there was nothing to place in that cell. With fill_value=0 the cell becomes 0.0 and the other values are unchanged. With sort=False the column order follows first appearance in the data; in this example the order of appearance happened to match the sorted order for rows, so check on your own data before relying on it.
Unstacking by level 0 gives the transpose of this table (conditions as rows, participants as columns). Unstacking a DataFrame instead of a Series adds a top column level holding the original column names: df.set_index(["participant","condition"]).unstack() produces MultiIndex columns ("score", "control"), ("score", "high") and ("score", "low"). Select one measure with wide["score"] to drop that top level.
The dtype stays float64 here because the scores are floats. When an integer Series is unstacked and a cell is missing, NaN forces the result to float64: a Series of the integers 1, 2, 3 on a MultiIndex with one absent pair came back as float64 columns (1.0, 2.0, 3.0 and NaN) when tested.
The data table below lists how unstack relates to the neighbouring reshaping methods, so you can pick the right one before writing code. For the multi-level indexes this produces, see MultiIndex in pandas.
Troubleshooting unstack
ValueError: Index contains duplicate entries, cannot reshape
Running unstack() on a Series or DataFrame whose index repeats a (participant, condition) pair raises ValueError: Index contains duplicate entries, cannot reshape (message captured from pandas 3.1.1). A table can only hold one value per cell, so the pair must be unique. In research data this usually means repeated measurements or a data-entry duplicate. Decide first which it is. If repeats are legitimate, aggregate them before unstacking: dup.groupby(level=[0,1]).mean().unstack() returns the same participant-by-condition table as the earlier example. The user guide also points to pivot_table() for data with duplicate pairs, whereas pivot() needs unique index/column pairs.
Unexpected NaN cells
NaN appears when subgroups do not share the same labels, as in the P2 example. Count them with wide.isna().sum() and decide whether they are missing by design, before filling them.
Wrong level unstacked
The default is the last level. If the table comes out the wrong way round, name the level: unstack("condition"). Check g.index.names first; a level with no name can only be addressed by number.
Column labels carry an extra header
The columns keep the name of the unstacked level (condition above). Clear it with wide.columns.name = None, then reset_index() to get a plain table for CSV export. When you unstacked a DataFrame, use wide.columns = ["_".join(c) for c in wide.columns] or select the top level first to avoid tuple column names.
Rows come back sorted
Because unstack() sorts by default, row order can differ from the input. Pass sort=False to order by first appearance, or call sort_index() explicitly so the intent is visible to a reader of your script.
Free alternatives and related methods
All of these ship with pandas, which is free and open source. The table in the dataset section below gives the comparison, and the prose here explains when to use each.
- DataFrame.pivot: starts from columns rather than an index, and requires unique index/columns pairs. See pandas pivot.
- pivot_table: the route the user guide gives for duplicate pairs, since it aggregates them.
- DataFrame.stack: the inverse, moving column labels into the index. The reverse trip from wide to long for modelling or plotting is also covered by pandas melt.
- groupby then unstack: the pattern used on this page; it is a two-step version of pivot_table that keeps you in control of the aggregation.
Once tables are wide, joining or appending them is the next step; see pandas concat.
Frequently asked questions
What does unstack do in pandas?
It pivots a level of a hierarchical index into the column labels, returning a DataFrame when the index is a MultiIndex and a Series otherwise. By default it moves the last index level (level=-1).
How do I unstack pandas data by a specific level?
Pass the level number or name to level, for example s.unstack(level=0) or s.unstack("participant"). A list of levels is allowed, but names and numbers cannot be mixed in the same list.
What is the difference between stack and unstack?
They are inverses: stack() moves column labels into the index and unstack() moves index labels into the columns. Both sort involved levels implicitly, so a round trip returns a sorted copy of the original.
How do I replace the NaN values unstack creates?
Use fill_value, for example g.unstack(fill_value=0), or call fillna() afterwards. Only use a placeholder if it is a meaningful value for your measurement.
Why do I get “Index contains duplicate entries, cannot reshape”?
The index has the same label pair more than once. Aggregate duplicates with groupby first, or use pivot_table().
Sources
- pandas documentation, DataFrame.unstack, version 3.1.1, checked 2026-11-14.
- pandas user guide, Reshaping and pivot tables, checked 2026-11-14.
- pandas, Installation, checked 2026-11-14.
- Worked example outputs and the error message: run by the author with pandas 3.1.1, 2026-11-14.
Data: pandas reshaping methods compared: unstack, pivot, pivot_table and stack
Compares four pandas reshaping methods by what they take as input, whether they accept duplicate index pairs, what they return and which method reverses them. Compiled from the pandas 3.1.1 DataFrame.unstack API page and the pandas reshaping user guide, plus the duplicate-entry behaviour of unstack tested by running pandas 3.1.1.
| Method | Reshapes | Duplicate index pairs | Returns | Inverse |
|---|---|---|---|---|
| DataFrame.unstack | Index level (MultiIndex) to columns | No: raises ValueError (checked in pandas 3.1.1) | DataFrame, or Series for a single-level index | DataFrame.stack |
| DataFrame.pivot | Existing columns used as index, columns and values | No: requires unique index/columns pairs | DataFrame | none stated on the pages read |
| DataFrame.pivot_table | Existing columns used as index, columns and values | Yes: the user guide points to it for duplicates | DataFrame | none stated on the pages read |
| DataFrame.stack | Column labels to the index | Not applicable | Series or DataFrame | DataFrame.unstack |
Sources
- pandas DataFrame.unstack (accessed 2026-11-14)
- pandas user guide: Reshaping and pivot tables (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







