Pandas DataFrame unstack() Method

Rate this post

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 unstack()

The unstack() method returns a re-shaped Multi-Level index DataFrame/Series with a new column level using inner-level labels.

The syntax for this method is as follows:

DataFrame.unstack(level=- 1, fill_value=None)
ParametersDescription
levelThis parameter is the level(s) to unstack. Levels can be a string, integer, or list. -1 by default (last level).
dropnaThis 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 unstack() method.

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

result = df.unstack(level=0)
print(result)
  • Line [1] creates a DataFrame with index labels and columns specified. The output saves to df.
  • Line [2] stacks the DataFrame. The df updates accordingly.
  • Line [3] outputs the DataFrame to the terminal.
  • Line [4] unstacks the stacked DataFrame. The output saves to result.
  • Line [5] outputs the result to the terminal (unstacked format).

Output

df

MicahAge8
 Grade7
PhilipAge7
 Grade5
dtype: int64  

result

 AgeGrade
Micah87
Philip75

DataFrame swap_axes()

The swapaxes() method swap axis 1 with axis 2. This parameter returns the called DataFrame/Series.

The syntax for this method is as follows:

DataFrame.swapaxes(axis1, axis2, copy=True)
axis1, axis2If zero (0) or index is selected, apply to each column. Default is 0 (column). If zero (1) or columns, apply to each row.
copyIf True, a copy of the original DataFrame/Series creates. True, by default. If False, the updates occur on the original DataFrame/Series.

We have six (6) book titles and associated details that save to a DataFrame. The np.random.randint() method retrieves the number of books sold.

index = [('Mystery', 'Sharp Objects', 1982), ('Mystery', 'A Murder', 1973), ('Mystery', 'Wanted', 1990),
         ('Fiction', 'Thirst', 1992), ('Fiction', 'The Time Keeper', 2014), ('Fiction', 'Eligible', 1997)]
m_index = pd.MultiIndex.from_tuples(index)
num_sold = np.random.randint(5,250,size=6)

df = pd.DataFrame({'Sold': num_sold}, index=m_index)
print(df)

result = df.swapaxes(1, 0)
print(result)
  • Line [1] creates a List of tuples. Each tuple contains three (3) values. The output saves to the index.
  • Line [2] creates a MultiIndex from the list of tuples created on line [1] and saves it to m_index.
  • Line [3] generates five (5) random integers between the specified range and saves them to num_sold.
  • Line [4] creates a DataFrame from the variables created on lines [1-3] and saves to df.
  • Line [5] outputs the DataFrame to the terminal.
  • Line [6] swaps out the axes as specified. The output saves to result.
  • Line [7] outputs the result to the terminal.

Output

df

   Sold
MysterySharp Objects198276
 A Murder1973114
 Wanted1990244
FictionThirst1992153
 The Time Keeper2014207
 Eligible1997175

result

 MysteryFiction
 Sharp ObjectsA MurderWantedThirstThe Time KeeperEligible
 198219731990199220141997
Sold76114244153207175

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.