Stack & Unstack

Python · Reshaping & Workflow

Theory

stack() and unstack() reshape using the index instead of columns. unstack() moves the innermost row-index level into the columns: after s = df.groupby(['city', 'quarter'])['amount'].sum(), which has a two-level (city, quarter) MultiIndex, s.unstack() gives one row per city and one column per quarter. unstack('city') or unstack(0) moves a different level, and fill_value=0 fills combinations that did not exist.

stack() does the opposite: it moves the column labels into the innermost row-index level, turning a wide table into a long Series with a MultiIndex. In pandas 2.x stack drops missing values by default (a future_stack=True option previews the newer behaviour). In practice unstack is most common right after a multi-key groupby, to view the result as a grid, and reset_index() turns any MultiIndex result back into ordinary columns.

Why we use it

Multi-key groupbys produce long results with a MultiIndex that are hard to read. unstack turns them into a grid in one call, and stack goes back, without having to name index and columns as pivot does.

When to use it

Use unstack directly after groupby on two or more keys, when you want one key across the columns. Use pivot_table when starting from plain columns, and melt for column-to-row reshaping of ordinary DataFrames.

How it works

  1. Series with MultiIndex (city, quarter)
  2. Pick the level to move: innermost by default
  3. unstack(): that level's values become columns
  4. Some combinations missing? Yes: fill_value=0 or leave NaN. No: Grid is complete.
  5. Grid: cities x quarters (stack() reverses it)

Syntax

s.unstack(level=-1, fill_value=None)
df.stack()
df.groupby(['k1', 'k2'])['v'].sum().unstack(fill_value=0)
df.reset_index()

Example

grid = df.groupby(['city', 'quarter'])['amount'].sum().unstack(fill_value=0)
print(grid)

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic