TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial…

Follow publication

Member-only story

Reshaping a DataFrame with Pandas stack() and unstack()

Robin Chan
TDS Archive
Published in
5 min readMar 11, 2022
Photo by pine watt on Unsplash

Reshaping is often needed when you work with datasets that contain variables with some kinds of sequences, say, time-series data.

Source from University of Virginia, Research Data Service [1]

Pandas provides various built-in methods for reshaping DataFrame. Among them, stack() and unstack() are the 2 most popular methods for restructuring columns and rows (also known as index).

  • stack(): stack the prescribed level(s) from column to row.
  • unstack(): unstack the prescribed level(s) from row to column. The inverse operation from stack.
Pandas stack() and unstack() (image by author)

stack() and unstack() seem fairly straightforward to use, but there are still some tricks you should know to speed up your data analysis. In this article, you’ll learn Pandas tricks to deal with the following use cases:

  1. Single level
  2. Multiple levels: simple case
  3. Multiple levels: missing values
  4. Multiple levels: specify a level to…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Robin Chan
Robin Chan

No responses yet

Write a response