บทนำ
ใช้คุณสมบัติ MultiIndex.codes เพื่อดึงตำแหน่ง (index) ของแต่ละป้ายกิจในระดับที่สอดคล้อง
ขั้นตอน
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 location of each label in Multi-index...\n", multiIndex.codes)
ตัวอย่างโค้ดเต็ม
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 levels in Multi-index...\n", multiIndex.levels)
print("\nThe location of each label in Multi-index...\n", multiIndex.codes)
ผลลัพธ์
The Multi-index...
MultiIndex([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris'), (5, 'Keiron')],
names=['ranks', 'student'])
The levels in Multi-index...
[[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
The location of each label in Multi-index...
[[0, 1, 2, 3, 4], [2, 4, 1, 0, 3]]
คำอธิบาย
codesคืนค่า list of arrays: ระดับ 0 →[0,1,2,3,4], ระดับ 1 →[2,4,1,0,3]- ระดับ 0: ค่า 1,2,3,4,5 อยู่ตำแหน่ง 0,1,2,3,4 ใน level 0 (เรียงแล้ว)
- ระดับ 1: 'John' อยู่ตำแหน่ง 2, 'Tim' ตำแหน่ง 4, 'Jacob' ตำแหน่ง 1, 'Chris' ตำแหน่ง 0, 'Keiron' ตำแหน่ง 3 ใน level 1 (เรียง alphabet)
- codes ใช้สำหรับการจัดเก็บภายในและการคำนวณที่เร็ว