บทนำ
ใช้ get_loc_level() แบบค่าเริ่มต้น (drop_level=True) เพื่อหาตำแหน่งและดัชนีที่สไลด์ได้ โดยลบระดับที่ค้นหาออก
ขั้นตอน
1. นำเข้าไลบรารีและสร้าง MultiIndex
import pandas as pd
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')], names=['One', 'Two'])
2. หาตำแหน่งและสไลด์ (ค่าเริ่มต้น drop_level=True)
print("\nGet the location and sliced index...\n", multiIndex.get_loc_level('r'))
ตัวอย่างโค้ดเต็ม
import pandas as pd
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')], names=['One', 'Two'])
print("The MultiIndex...\n", multiIndex)
print("\nThe levels in MultiIndex...\n", multiIndex.levels)
print("\nGet the location and sliced index...\n", multiIndex.get_loc_level('r'))
ผลลัพธ์
The MultiIndex...
MultiIndex([('p', 's'), ('q', 't'), ('r', 'r'), ('r', 'v'), ('s', 'w'), ('s', 'x')],
names=['One', 'Two'])
The levels in MultiIndex...
[['p', 'q', 'r', 's'], ['r', 's', 't', 'v', 'w', 'x']]
Get the location and sliced index...
(slice(2, 4, None), Index(['r', 'v'], dtype='object', name='Two'))
คำอธิบาย
- คืนค่า:
(slice(2, 4, None), Index(['r', 'v'], name='Two')) - ระดับที่ค้นหา ('One') ถูกลบออก เหลือเฉพาะระดับ 'Two' ใน Index ที่คืนมา
- เหมาะสำหรับการ indexing ต่อยอด