
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Multiple Levels Using Level Names in Python
To remove multiples levels using the level names and return the index, use the multiIndex.droplevel(). Set the level names 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 multiple levels using the level names. We have passed the names of the levels to be removed as a parameter −
print("\nDropping multiple level...\n", multiIndex.droplevel(['a', 'd']))
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 multiple levels using the level names # We have passed the names of the levels to be removed as a parameter print("\nDropping multiple level...\n", multiIndex.droplevel(['a', 'd']))
Output
This will produce the following output −
Multi-index... MultiIndex([( 5, 15, 25, 35),(10, 20, 30, 40)],names=['a', 'b', 'c', 'd']) Dropping multiple level... MultiIndex([(15, 25),(20, 30)],names=['b', 'c'])
Advertisements