- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas - Get the Integer number of levels in this MultiIndex
To get the Integer number of levels in this MultiIndex, use the MultiIndex.nlevels property in Pandas. At first, import the required libraries −
import pandas as pd
MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
The "names" parameter sets the names for each of the index levels. The from_arrays() uis used to create a Multiindex −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
Get the integer number of levels in Multiindex −
print("\nThe number of levels in Multi-index...\n",multiIndex.nlevels)
Example
Following is the code −
import pandas as pd # MultiIndex is a multi-level, or hierarchical, index object for pandas objects # Create arrays arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']] # The "names" parameter sets the names for each of the index levels # The from_arrays() uis used to create a Multiindex multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student')) # display the Multiindex print("The Multi-index...\n",multiIndex) # get the integer number of levels in Multiindex print("\nThe number of levels in Multi-index...\n",multiIndex.nlevels) # get the levels in Multiindex print("\nThe levels in Multi-index...\n",multiIndex.levels)
Output
This will produce the following output −
The Multi-index... MultiIndex([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris'), (5, 'Keiron')], names=['ranks', 'student']) The number of levels in Multi-index... 2 The levels in Multi-index... [[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
Advertisements
To Continue Learning Please Login
Login with Google