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.
DataFrame.droplevel(level, axis=0)
level
: This can be an integer, string, or a list-like object.
level
is an integer, it will be treated as a positional index.level
is a string, it must be the name of a level.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.This method returns the DataFrame with the specified levels removed.
import pandas as pdindex = 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.indexindex.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)
pandas
.droplevel()
method. The first level is 0
. Since it is a column index, we have axis=1
.droplevel()
method. The second level is 1
. Since it is a column index, we have axis=1
.