Preparation
Before any data manipulation can occur, two (2) new libraries will require installation.
- The Pandas library enables access to/from a DataFrame.
- The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.
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
DataFrame stack()
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)
- Line [1] creates a DataFrame with index labels and columns specified. This output saves to
df
. - Line [2] outputs the DataFrame to the terminal.
- Line [3] stacks the DataFrame and saves the output to
result
. - Line [4] outputs the result to the terminal (stacked format).
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.