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

เกิดอะไรขึ้นเมื่อ Index ที่ระบุไม่มีใน Series Pandas Python

เมื่อใช้ Custom Index ใน Series การเข้าถึงด้วย Label ที่ไม่มีอยู่จะ Raise KeyError

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


import pandas as pd

my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)

print("The series contains following elements")
print(my_series)

print("\nAccessing elements using customized index")
print(my_series['mm'])  # 'mm' ไม่อยู่ใน Index

ผลลัพธ์


The series contains following elements
ab    34
mn    56
gh    78
kl    90
wq   123
az    45
dtype: int64

Accessing elements using customized index
Traceback (most recent call last):
  ...
KeyError: 'mm'

คำอธิบาย

  • สร้าง Series พร้อม Custom Index

  • พยายามเข้าถึง my_series['mm'] แต่ 'mm' ไม่อยู่ใน Index

  • Pandas Raise KeyError: 'mm'

วิธีป้องกัน/จัดการ KeyError

วิธีCodeพฤติกรรม
.get()s.get('mm')คืน None (หรือ Default) แทน Error
.get() with Defaults.get('mm', 0)คืน 0 ถ้าไม่มี Key
in Operator'mm' in s.indexTrue/False ตรวจสอบก่อนเข้าถึง
try/excepttry: v=s['mm'] except KeyError: v=Noneจัดการ Exception
.loc[]s.loc['mm']ยัง Raise KeyError (Explicit Label-based)
.iloc[]s.iloc[0]Position-based, ไม่ Error จาก Label

แนวทางปฏิบัติที่ดี


# 1. ตรวจสอบก่อนเข้าถึง
if 'mm' in my_series.index:
    val = my_series['mm']

# 2. ใช้ .get() สำหรับ Optional Lookup
val = my_series.get('mm', default_value)

# 3. ใช้ .loc/.iloc ให้ชัดเจน
val = my_series.loc['mn']      # Label-based
val = my_series.iloc[1]        # Position-based

# 4. Reindex ก่อนใช้ (สร้าง Index ใหม่ พร้อม Fill Value)
my_series = my_series.reindex(['ab', 'mn', 'mm'], fill_value=0)
# mm จะมีค่า 0 แทน NaN/Error

ข้อสังเกต: Integer Index vs Custom Index


# Default Integer Index
s1 = pd.Series([10, 20, 30])
print(s1[0])    # 10 (Position และ Label ตรงกัน)
print(s1[5])    # KeyError: 5 (Label 5 ไม่มี)

# Custom String Index
s2 = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print(s2['a'])  # 10
print(s2[0])    # 10 (Pandas Fallback ไป Positional สำหรับ Integer)

Warning: ใช้ .iloc และ .loc แทน Bracket `[]` โดยตรง เพื่อความชัดเจนและป้องกัน Bug