Pandas DataFrame droplevel() 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 droplevel()

The droplevel() method removes the specified index or column from a DataFrame/Series. This method returns a DataFrame/Series with the said level/column removed.

httpv://www.youtube.com/watch?v=embed/PMKuZoQoYE0

The syntax for this method is as follows:

DataFrame.droplevel(level, axis=0)
ParameterDescription
levelIf the level is a string, this level must exist. If a list, the elements must exist and be a level name/position of the index.
axisIf zero (0) or index is selected, apply to each column. Default is 0 (column). If zero (1) or columns, apply to each row.

For this example, we generate random stock prices and then drop (remove) level Stock-B from the DataFrame.

nums = np.random.uniform(low=0.5, high=13.3, size=(3,4))
df_stocks = pd.DataFrame(nums).set_index([0, 1]).rename_axis(['Stock-A', 'Stock-B'])
print(df_stocks)

result = df_stocks.droplevel('Stock-B')
print(result)
  • Line [1] generates random numbers for three (3) lists within the specified range. Each list contains four (4) elements (size=3,4). The output saves to nums.
  • Line [2] creates a DataFrame, sets the index, and renames the axis. This output saves to df_stocks.
  • Line [3] outputs the DataFrame to the terminal.
  • Line [4] drops (removes) Stock-B from the DataFrame and saves it to the result variable.
  • Line [5] outputs the result to the terminal.

Output

df_stocks

  23
Stock-AStock-B  
12.32771010.862572  7.105198 8.295885
11.4748721.563040   5.915501 6.102915

result

 23
Stock-A  
12.3277107.105198 8.295885
11.4748725.915501 6.102915

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.