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
levelis an integer, it will be treated as a positional index. - If
levelis a string, it must be the name of a level. - If
levelis a list-like object, the elements of the list must be the names or positional indexes of levels.
- If
-
axis: This indicates the axis along which the levels are dropped or removed.0orindexindicates that the levels are removed in the columns.1orcolumnsindicates that the levels are removed in the rows.
Return value
This method returns the DataFrame with the specified levels removed.
Example
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)
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 is0. Since it is a column index, we haveaxis=1. - Line 21: We drop the second level of the index using the
droplevel()method. The second level is1. Since it is a column index, we haveaxis=1.