บทนำ
ใช้คุณสมบัติ MultiIndex.levshape เพื่อดึงทูเพิลที่มีความยาวของแต่ละระดับ
ขั้นตอน
1. นำเข้าไลบรารีและสร้าง MultiIndex
import pandas as pd
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
2. ดึงทูเพิลความยาวแต่ละระดับ
print("\nThe tuple with the length of each level in a Multi-index...\n", multiIndex.levshape)
ตัวอย่างโค้ดเต็ม
import pandas as pd
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
print("The Multi-index...\n", multiIndex)
print("\nThe number of levels in Multi-index...\n", multiIndex.nlevels)
print("\nThe levels in Multi-index...\n", multiIndex.levels)
print("\nThe tuple with the length of each level in a Multi-index...\n", multiIndex.levshape)
ผลลัพธ์
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']]
The tuple with the length of each level in a Multi-index...
(5, 5)
คำอธิบาย
levshapeคืนค่า tuple:(len(level_0), len(level_1), ...)- ระดับ 0 มีค่า unique 5 ค่า (1-5), ระดับ 1 มีค่า unique 5 ค่า (5 ชื่อ)
- ต่างจาก
len(multiIndex)ที่นับจำนวนแถว (codes)