แนวคิด
เมธอด Index.get_loc(key) คืนค่าตำแหน่ง (integer index) ของคอลัมน์ที่ระบุ ทำงานกับ df.columns ซึ่งเป็น Index object
ตัวอย่างโค้ด
import pandas as pd
df = pd.DataFrame({
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
})
print("DataFrame:\n", df)
print("\nColumns:", df.columns)
# หา index ของคอลัมน์ต่างๆ
for col in ['z', 'x', 'y']:
idx = df.columns.get_loc(col)
print(f"Index ของคอลัมน์ '{col}': {idx}")
ผลลัพธ์
DataFrame:
x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1
Columns: Index(['x', 'y', 'z'], dtype='object')
Index ของคอลัมน์ 'z': 2
Index ของคอลัมน์ 'x': 0
Index ของคอลัมน์ 'y': 1
กรณีพิเศษ
# ถ้ามีคอลัมน์ซ้ำกัน (duplicate columns)
df_dup = pd.DataFrame([[1,2,3]], columns=['A', 'B', 'A'])
print(df_dup.columns.get_loc('A')) # คืน slice object: slice(0, 3, 2) หมายถึงตำแหน่ง 0 และ 2
# ใช้ get_indexer สำหรับหลายคอลัมน์พร้อมกัน
indices = df.columns.get_indexer(['x', 'z']) # คืน array([0, 2])
การประยุกต์ใช้
- ใช้กับ
ilocที่ต้องการตำแหน่งตัวเลข:df.iloc[:, df.columns.get_loc('col_name')] - ช่วยในการเขียนโค้ดที่ dynamic ไม่ต้อง hard-code index