To remove a level using the name of the level and return the index, use the multiIndex.droplevel() method in Pandas. Set the name of the level to be removed as parameter.
At first, import the required libraries -
import pandas as pd
Create a multi-index. The names parameter sets the names for the levels in the index
multiIndex = pd.MultiIndex.from_arrays([[5, 10], [15, 20], [25, 30], [35, 40]], names=['a', 'b', 'c', 'd'])
Display the multi-index −
print("Multi-index...\n", multiIndex)
Dropping a level using the level name. We have passed the name of the level to be removed as a parameter −
print("\nDropping a level...\n", multiIndex.droplevel('b'))
Example
Following is the code −
import pandas as pd # Create a multi-index # The names parameter sets the names for the levels in the index multiIndex = pd.MultiIndex.from_arrays([[5, 10], [15, 20], [25, 30], [35, 40]], names=['a', 'b', 'c', 'd']) # display the multi-index print("Multi-index...\n", multiIndex) # Dropping a level using the level name # We have passed the name of the level to be removed as a parameter print("\nDropping a level...\n", multiIndex.droplevel('b'))
Output
This will produce the following output −
Multi-index... MultiIndex([( 5, 15, 25, 35),(10, 20, 30, 40)],names=['a', 'b', 'c', 'd']) Dropping a level... MultiIndex([( 5, 25, 35),(10, 30, 40)],names=['a', 'c', 'd'])