🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpandas

pandas Documentation

LOADING ENGINE...

df.stack()

AI & DATA SCIENCE // df-stack

df.stack() pivots the innermost level of a DataFrame's columns into a new innermost level of the row index, converting from wide to a taller, more compact form.

Syntax

df.stack(level=-1, dropna=True)

Deep Dive Course

stack() moves column labels down into the index, producing a Series, for a simple DataFrame, or a DataFrame with a MultiIndex, where each combination of the original row label and column label becomes its own row — conceptually similar to melt(), but working at the index/columns structural level rather than reshaping via specific column names, and it's specifically designed to pair with hierarchical (MultiIndex) columns. By default, dropna=True drops any resulting rows that would be entirely NaN, which is common after stacking a DataFrame that had some genuinely missing cells.

1Understanding df.stack()

stack() moves column labels down into the index, producing a Series, for a simple DataFrame, or a DataFrame with a MultiIndex, where each combination of the original row label and column label becomes its own row — conceptually similar to melt(), but working at the index/columns structural level rather than reshaping via specific column names, and it's specifically designed to pair with hierarchical (MultiIndex) columns. By default, dropna=True drops any resulting rows that would be entirely NaN, which is common after stacking a DataFrame that had some genuinely missing cells.

💡

stack() and unstack() are exact inverses of each other — stack() moves the innermost column level down into the index, and unstack() moves the innermost index level back up into columns, so applying one immediately after the other, when nothing else changes in between, returns you to the original shape.

editor.html
import pandas as pd

df = pd.DataFrame({"math": [90, 85], "science": [95, 80]}, index=["Alice", "Bob"])
print(df.stack())
localhost:3000

2Practical Example

Here is a real-world application of df.stack() showing how it is used in production Pandas code.

editor.html
import pandas as pd

df = pd.DataFrame({"math": [90, 85]}, index=["Alice", "Bob"])
stacked = df.stack()
unstacked = stacked.unstack()
print(unstacked.equals(df))
localhost:3000

3Best Practices

Follow these guidelines when working with df.stack():

1. Use stack() when you specifically need to work with hierarchical (MultiIndex) columns, converting them into an equally hierarchical row index

2. Pass dropna=False if entirely-NaN rows produced by stacking sparse data should be kept rather than silently dropped

3. Reach for melt() instead of stack() when the reshaping is more naturally described by specific column names rather than the index/columns structure itself

⚠️

Tip: stack() and unstack() are exact inverses of each other — stack() moves the innermost column level down into the index, and unstack() moves the innermost index level back up into columns, so applying one immediately after the other, when nothing else changes in between, returns you to the original shape.

editor.html
import pandas as pd

df = pd.DataFrame({"math": [90, 85], "science": [95, 80]}, index=["Alice", "Bob"])
print(df.stack())
localhost:3000

Examples

Example 01Basic Usage
import pandas as pd

df = pd.DataFrame({"math": [90, 85], "science": [95, 80]}, index=["Alice", "Bob"])
print(df.stack())
Example 02Advanced Example
import pandas as pd

df = pd.DataFrame({"math": [90, 85]}, index=["Alice", "Bob"])
stacked = df.stack()
unstacked = stacked.unstack()
print(unstacked.equals(df))

Best Practices

  • Use stack() when you specifically need to work with hierarchical (MultiIndex) columns, converting them into an equally hierarchical row index
  • Pass dropna=False if entirely-NaN rows produced by stacking sparse data should be kept rather than silently dropped
  • Reach for melt() instead of stack() when the reshaping is more naturally described by specific column names rather than the index/columns structure itself

Interview Question

What's the relationship between df.stack() and df.unstack()?

Hint: Think about which direction each operation moves labels between the index and the columns.

They're exact inverse operations of each other: stack() takes the innermost level of the column labels and moves it down to become the innermost level of the row index, producing a taller, more compact structure. unstack() does the reverse, taking the innermost level of the row index and pivoting it back up to become column labels. Applying stack() followed immediately by unstack(), with nothing else changing in between, reconstructs the original DataFrame's shape exactly, which is why they're described as inverses of one another.

Exercises

MediumPractice using df.stack() in a real scenario.
View Solution
import pandas as pd

df = pd.DataFrame({"math": [90, 85], "science": [95, 80]}, index=["Alice", "Bob"])
print(df.stack())

Frequently Asked Questions

What's the relationship between df.stack() and df.unstack()?

They're exact inverse operations of each other: stack() takes the innermost level of the column labels and moves it down to become the innermost level of the row index, producing a taller, more compact structure. unstack() does the reverse, taking the innermost level of the row index and pivoting it back up to become column labels. Applying stack() followed immediately by unstack(), with nothing else changing in between, reconstructs the original DataFrame's shape exactly, which is why they're described as inverses of one another.

Related Functions

df-unstackpd-meltpd-multiindex