What is the drop_level method in pandas?

Overview

The drop_level method is used to remove the given indexes or column levels from the DataFrame.

Note: Click here to learn more about the pandas library.

Syntax

DataFrame.droplevel(level, axis=0)

Parameters

  • level: This can be an integer, string, or a list-like object.

    • If level is an integer, it will be treated as a positional index.
    • If level is a string, it must be the name of a level.
    • If level is a list-like object, the elements of the list must be the names or positional indexes of levels.
  • axis: This indicates the axis along which the levels are dropped or removed.

    • 0 or index indicates that the levels are removed in the columns.
    • 1 or columns indicates that the levels are removed in the rows.

Return value

This method returns the DataFrame with the specified levels removed.

Example

import pandas as pd
index = pd.MultiIndex.from_tuples([("Level 1", "Level 1"),
("Level 2", "Level 2"),
("Level 2", "Level 3")])
prog_langs = [["Java","Golang","C++"],["R","Julia","Python"]]
df = pd.DataFrame(prog_langs, columns=index)
index = df.index
index.name = "Programming Languages"
print("The dataframe is --- \n", df)
print("-"*8)
print("Removing the first level column wise")
new_df = df.droplevel(0, axis=1)
print(new_df)
print("-"*8)
print("Removing the second level column wise")
new_df = df.droplevel(1, axis=1)
print(new_df)

Explanation

  • Line 1: We import pandas.
  • Lines 3–5: We define the different indexes for the DataFrame.
  • Line 7: We define the dummy data for the DataFrame.
  • Line 9 - We create pandas DataFrame from the dummy data and the index.
  • Line 14: We print the DataFrame.
  • Line 17: We drop the first level of the index using the droplevel() method. The first level is 0. Since it is a column index, we have axis=1.
  • Line 21: We drop the second level of the index using the droplevel() method. The second level is 1. Since it is a column index, we have axis=1.

Free Resources