Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Get the Integer number of levels in this MultiIndex
To get the integer number of levels in a MultiIndex, use the MultiIndex.nlevels property in Pandas. This property returns the depth of the hierarchical index structure.
Syntax
MultiIndex.nlevels
This property returns an integer representing the number of levels in the MultiIndex.
Creating a MultiIndex
First, let's create a MultiIndex using arrays and the from_arrays() method ?
import pandas as pd
# Create arrays for MultiIndex
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
# Create MultiIndex with named levels
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
# Display the MultiIndex
print("The Multi-index...")
print(multiIndex)
The Multi-index...
MultiIndex([(1, 'John'),
(2, 'Tim'),
(3, 'Jacob'),
(4, 'Chris'),
(5, 'Keiron')],
names=['ranks', 'student'])
Getting the Number of Levels
Use the nlevels property to get the integer number of levels ?
import pandas as pd
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
# Get the number of levels
print("The number of levels in Multi-index:")
print(multiIndex.nlevels)
# Additional information: get the actual levels
print("\nThe levels in Multi-index:")
print(multiIndex.levels)
The number of levels in Multi-index: 2 The levels in Multi-index: [[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
Practical Example with DataFrame
Here's how nlevels works with a DataFrame that has a MultiIndex ?
import pandas as pd
# Create a DataFrame with MultiIndex
arrays = [['A', 'A', 'B', 'B'], ['X', 'Y', 'X', 'Y']]
index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
df = pd.DataFrame({'values': [10, 20, 30, 40]}, index=index)
print("DataFrame with MultiIndex:")
print(df)
print(f"\nNumber of index levels: {df.index.nlevels}")
DataFrame with MultiIndex:
values
first second
A X 10
Y 20
B X 30
Y 40
Number of index levels: 2
Conclusion
The nlevels property provides a quick way to determine the depth of a MultiIndex structure. This is useful for validation and dynamic operations on hierarchical data structures in Pandas.
Advertisements
