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 a tuple with the length of each level from MultiIndex
To get a tuple with the length of each level from MultiIndex, use the MultiIndex.levshape property in Pandas. This property returns a tuple where each element represents the number of unique values in the corresponding level.
Creating a MultiIndex
First, let's create a MultiIndex with two levels ?
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'))
print("The Multi-index...\n", multiIndex)
The Multi-index...
MultiIndex([(1, 'John'),
(2, 'Tim'),
(3, 'Jacob'),
(4, 'Chris'),
(5, 'Keiron')],
names=['ranks', 'student'])
Getting Level Shapes
Use the levshape property to get the length of each level ?
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 tuple with length of each level
print("The tuple with the length of each level:", multiIndex.levshape)
print("Number of levels:", multiIndex.nlevels)
print("Levels content:", multiIndex.levels)
The tuple with the length of each level: (5, 5) Number of levels: 2 Levels content: [[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
Example with Duplicate Values
Let's see how levshape works with duplicate values in levels ?
import pandas as pd
# Create MultiIndex with duplicate values
arrays = [[1, 1, 2, 2, 3], ['A', 'B', 'A', 'C', 'B']]
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('level1', 'level2'))
print("MultiIndex with duplicates:")
print(multiIndex)
print("\nLevel shapes:", multiIndex.levshape)
print("Unique values in level 0:", multiIndex.levels[0])
print("Unique values in level 1:", multiIndex.levels[1])
MultiIndex with duplicates:
MultiIndex([(1, 'A'),
(1, 'B'),
(2, 'A'),
(2, 'C'),
(3, 'B')],
names=['level1', 'level2'])
Level shapes: (3, 3)
Unique values in level 0: [1, 2, 3]
Unique values in level 1: ['A', 'B', 'C']
Conclusion
The levshape property returns a tuple showing the number of unique values in each level of a MultiIndex. This is useful for understanding the structure and dimensions of hierarchical indices in pandas.
Advertisements
