Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - หาตำแหน่งและดัชนีที่แบ่งสไลด์สำหรับป้ายกิจ/ระดับที่ร้องขอ แต่ไม่ลบระดับ

บทนำ

ใช้ get_loc_level() พร้อม drop_level=False เพื่อหาตำแหน่งและดัชนีที่สไลด์ได้ โดยเก็บระดับไว้

ขั้นตอน

1. นำเข้าไลบรารีและสร้าง MultiIndex

import pandas as pd
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')], names=['One', 'Two'])

2. หาตำแหน่งและสไลด์ โดยไม่ลบระดับ

print("\nGet the location and sliced index (avoid dropping the level)...\n",
      multiIndex.get_loc_level('r', drop_level=False))

ตัวอย่างโค้ดเต็ม

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 (avoid dropping the level)...\n",
      multiIndex.get_loc_level('r', drop_level=False))

ผลลัพธ์

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 (avoid dropping the level)...
(slice(2, 4, None), MultiIndex([('r', 'r'), ('r', 'v')], names=['One', 'Two']))

คำอธิบาย

  • คืนค่าเป็น tuple: (slice_object, sliced_MultiIndex)
  • slice(2, 4, None) หมายถึง index 2 ถึง 3 (ไม่รวม 4)
  • drop_level=False ทำให้ MultiIndex ที่คืนมายังคงมีทุกระดับ
  • ค้นหา 'r' ในระดับแรก (One) พบที่ตำแหน่ง 2, 3