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
Python Pandas - Get the levels in MultiIndex
To get the levels in MultiIndex, use the MultiIndex.levels property in Pandas. MultiIndex is a multi-level, or hierarchical, index object for pandas objects that allows you to work with higher dimensional data efficiently.
Syntax
MultiIndex.levels
This property returns a list of arrays, where each array contains the unique values for that index level.
Creating a MultiIndex
First, let's create a MultiIndex from arrays ?
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 Levels
Now, let's extract the levels from our MultiIndex ?
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'))
# Get the levels in MultiIndex
print("The levels in Multi-index...")
print(multiIndex.levels)
The levels in Multi-index... [[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
Understanding the Output
The levels property returns a list containing:
- First level: [1, 2, 3, 4, 5] - the unique values from the 'ranks' level
- Second level: ['Chris', 'Jacob', 'John', 'Keiron', 'Tim'] - the unique values from the 'student' level (sorted alphabetically)
Accessing Individual Levels
You can access specific levels using indexing ?
import pandas as pd
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
# Access first level (ranks)
print("First level (ranks):", multiIndex.levels[0])
# Access second level (student)
print("Second level (student):", multiIndex.levels[1])
First level (ranks): [1, 2, 3, 4, 5] Second level (student): ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']
Conclusion
The MultiIndex.levels property provides access to the unique values at each level of a hierarchical index. Each level contains sorted unique values, making it useful for understanding the structure of your MultiIndex data.
