บทนำ
ใช้ MultiIndex.get_loc() เพื่อหาตำแหน่งของป้ายกิจเดี่ยวหรือทูเพิลของป้ายกิจใน MultiIndex
ขั้นตอน
1. นำเข้าไลบรารีและสร้าง MultiIndex
import pandas as pd
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('stuvwx')])
2. หาตำแหน่งของป้ายกิจ 's'
print("\nGet the locations in MultiIndex...\n", multiIndex.get_loc('s'))
ตัวอย่างโค้ดเต็ม
import pandas as pd
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('stuvwx')])
print("The MultiIndex...\n", multiIndex)
print("\nThe levels in MultiIndex...\n", multiIndex.levels)
print("\nGet the locations in MultiIndex...\n", multiIndex.get_loc('s'))
ผลลัพธ์
The MultiIndex...
MultiIndex([('p', 's'), ('q', 't'), ('r', 'u'), ('r', 'v'), ('s', 'w'), ('s', 'x')])
The levels in MultiIndex...
[['p', 'q', 'r', 's'], ['s', 't', 'u', 'v', 'w', 'x']]
Get the locations in MultiIndex...
slice(4, 6, None)
คำอธิบาย
get_loc('s')ค้นหา 's' ในระดับแรก (level 0)- พบ 's' ที่ตำแหน่ง 4 และ 5 → คืนค่า
slice(4, 6, None) - ถ้าค้นหาทูเพิล เช่น
get_loc(('s', 'w'))จะคืน integer position เดียว