How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?

Data in wide form is often easy to read for human eyes. However, you might need data in tidy/long form for data analysis. In Pandas there are a few ways to reshape a dataframe in wide form to a dataframe in long/tidy form. In this post we will see a simple example of converting a wide dataframe to long form using Pandas stack() function.

Pandas stack() function is designed to work with multi-indexed dataframe. The name stack refers to reorganizing data in side-by-side columns to stacking them vertically, i.e. wide to tall/long.

Let us first load Pandas and NumPy.

import pandas as pd
import numpy as np

In this example, we will generate data using random numbers using SciPy. Let us load scipy.stats and set random seed for reproducing the data.

from scipy.stats import nbinom
np.random.seed(seed=42)

We will generate random numbers from negative binomial distribution.

c1= nbinom.rvs(5, 0.3, size=3)
c2= nbinom.rvs(20, 0.3, size=3)
c3= nbinom.rvs(10, 0.3, size=3)

We will create a toy dataframe with three columns using the random numbers.

df=pd.DataFrame({"C1":c1,
                 "C2":c2,
                 "C3":c3})

Our data looks like this and you can see that we have the data in wide form.

df

        C1	C2	C3
0	15	51	18
1	11	31	34
2	7	29	31

Let us use Pandas stack() function to convert the data in wide form to long/tidy form. Pandas’ stack() function automatically uses all the columns and creates a new dataframe in tidy form. Note that the columns names in wide form are a variable now and the values are another variable.

df.stack()

0  C1    15
   C2    51
   C3    18
1  C1    11
   C2    31
   C3    34
2  C1     7
   C2    29
   C3    31
dtype: int64

Pandas’ stack() function creates tidy dataframe with multi-index. We can simplify it with Pandas’ reset_index() function as shown below.

df.stack().reset_index()

When we use reset_index() it automatically creates column names reflecting the levels of the multi-index dataframe.

	level_0	level_1	0
0	0	C1	15
1	0	C2	51
2	0	C3	18
3	1	C1	11
4	1	C2	31
5	1	C3	34
6	2	C1	7
7	2	C2	29
8	2	C3	31

Just as you guessed, Pandas also has complementary function unstack() and we will see examples of that soon.

This post is part of the series on Byte Size Pandas: Pandas 101, a tutorial covering tips and tricks on using Pandas for data munging and analysis.