บทนำ
ใช้ MultiIndex.get_locs() เพื่อหาตำแหน่ง (index positions) ของลำดับป้ายกิจที่กำหนดใน MultiIndex
ขั้นตอน
1. นำเข้าไลบรารีและสร้าง MultiIndex
import pandas as pd
multiIndex = pd.MultiIndex.from_arrays([list('pqrrst'), list('kytssp')])
2. หาตำแหน่งของป้ายกิจ 's'
print("\nGet the locations in MultiIndex...\n", multiIndex.get_locs('s'))
ตัวอย่างโค้ดเต็ม
import pandas as pd
multiIndex = pd.MultiIndex.from_arrays([list('pqrrst'), list('kytssp')])
print("The MultiIndex...\n", multiIndex)
print("\nThe levels in MultiIndex...\n", multiIndex.levels)
print("\nGet the locations in MultiIndex...\n", multiIndex.get_locs('s'))
ผลลัพธ์
The MultiIndex...
MultiIndex([('p', 'k'), ('q', 'y'), ('r', 't'), ('r', 's'), ('s', 's'), ('t', 'p')])
The levels in MultiIndex...
[['p', 'q', 'r', 's', 't'], ['k', 'p', 's', 't', 'y']]
Get the locations in MultiIndex...
[4]
คำอธิบาย
get_locs('s')ค้นหา 's' ในทุกระดับ คืนตำแหน่งที่พบ- พบ 's' ที่ระดับ 0 ตำแหน่ง 4 (คู่ ('s', 's')) และระดับ 1 ตำแหน่ง 3 (คู่ ('r', 's'))
- แต่ผลลัพธ์แสดง [4] แปลว่าค้นหาในระดับแรก (level 0) เป็นหลัก