Pandas DataFrame stack() Method – Be on the Right Side of Change (original) (raw)


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd import numpy as np


The stack() method returns a re-shaped Multi-Level index DataFrame/Series containing at minimum one (1) or more inner levels. A pivot occurs on the new levels using the columns of the DataFrame/Series.

💡 Note: If a single level, the output returns as a Series. If multi-level, the new level(s) are retrieved from the said levels and return a DataFrame.

The syntax for this method is as follows:

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

level This parameter is the level(s) to stack on the selected axis. Levels can be a string, integer, or list. By default, -1 (last level).
dropna This parameter determines if rows containing missing values drop. True, by default.

We have two (2) students with relevant details that save to a DataFrame. The code below displays the original DataFrame and the DataFrame using the stack() method.

df = pd.DataFrame([[8, 7], [7, 5]], index=['Micah', 'Philip'], columns=['Age', 'Grade']) print(df)

result = df.stack() print(result)

Output

df

| | Age | Grade | | | ------ | ----- | - | | Micah | 8 | 7 | | Philip | 7 | 5 |

result

Micah Age 8
Grade 7
Philip Age 7
Grade 5
dtype: int64

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.