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

การเข้าถึง Element ใน Series ด้วย Index (Default และ Custom) ใน Pandas Python

Pandas Series รองรับ 2 แบบ Index: Default Integer Index (0,1,2...) และ Custom Index (String, Datetime, etc.)

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


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['mn'])

print("\nAccessing elements using customized index")
print(my_series['az'])

ผลลัพธ์


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

Accessing elements using customized index
56

Accessing elements using customized index
45

คำอธิบาย

  • Custom Index: ใช้ Label เข้าถึง my_series['mn'] → 56

  • Default Index: ถ้าไม่ระบุ Index ใช้ 0,1,2,... เข้าถึง my_series[0]

Default vs Custom Index


# Default Integer Index
s_default = pd.Series([10, 20, 30])
print(s_default[0])    # 10 (Label 0 = Position 0)
print(s_default[1])    # 20

# Custom String Index
s_custom = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print(s_custom['a'])   # 10 (Label 'a')
print(s_custom['b'])   # 20

# Integer Index แต่เริ่มไม่ใช่ 0
s_int = pd.Series([10, 20, 30], index=[100, 200, 300])
print(s_int[100])      # 10 (Label 100)
print(s_int[0])        # 10 (Fallback ไป Position 0 - Ambiguous!)

Best Practice: ใช้ .loc และ .iloc

Methodประเภทตัวอย่างคำอธิบาย
.loc[]Label-baseds.loc['mn']เข้าถึงด้วย Label ชัดเจน ไม่ Ambiguous
.iloc[]Position-baseds.iloc[1]เข้าถึงด้วยตำแหน่ง (0-based) ชัดเจน
[]Mixeds['mn']Legacy, อาจสับสนกับ Integer Index

# แนะนำ: ใช้ .loc และ .iloc เสมอ
print(my_series.loc['mn'])   # 56 - Label 'mn'
print(my_series.iloc[1])     # 56 - Position 1
print(my_series.loc[['mn','az']])  # Multiple Labels
print(my_series.iloc[[1,5]])       # Multiple Positions

Slicing ด้วย Label vs Position


# Label Slicing (.loc) - Inclusive ทั้งสองข้าง
print(my_series.loc['mn':'kl'])
# mn    56
# gh    78
# kl    90

# Position Slicing (.iloc) - Exclusive ขวา
print(my_series.iloc[1:4])
# mn    56
# gh    78
# kl    90

สรุป: Custom Index ใช้ Label เข้าถึง ควรใช้ .loc[] สำหรับ Label และ .iloc[] สำหรับ Position เพื่อความชัดเจนและปลอดภัย