สามารถเข้าถึงหลาย Element พร้อมกันได้โดยส่ง List ของ Labels เข้าไปใน Bracket `[[...]]` (Double Brackets)
ตัวอย่างโค้ด
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 multiple elements using customized index")
print(my_series[['mn', 'az', 'wq', 'ab']])
ผลลัพธ์
The series contains following elements
ab 34
mn 56
gh 78
kl 90
wq 123
az 45
dtype: int64
Accessing multiple elements using customized index
mn 56
az 45
wq 123
ab 34
dtype: int64
คำอธิบาย
สร้าง Series พร้อม Custom Index
ใช้ Double Brackets:
my_series[['mn', 'az', 'wq', 'ab']]คืนค่า Series ใหม่ มีเฉพาะ Index ที่ร้องขอ ตามลำดับที่ระบุใน List
Index 'gh', 'kl' ไม่อยู่ใน List จึงไม่แสดง
Single vs Double Brackets
| Syntax | Input | Output | Use Case |
|---|---|---|---|
s['label'] | Single Label | Scalar Value | เข้าถึง 1 ค่า |
s[['l1','l2']] | List of Labels | Series | เลือกหลาย Column/Row |
s.loc[['l1','l2']] | List of Labels | Series | Explicit Label-based (แนะนำ) |
s.iloc[[0,2]] | List of Positions | Series | Position-based Selection |
ตัวอย่างเพิ่มเติม
# ใช้ .loc (แนะนำ - ชัดเจนกว่า)
subset = my_series.loc[['mn', 'az', 'wq', 'ab']]
# ใช้ .iloc (Position)
subset = my_series.iloc[[1, 5, 4, 0]] # Same result
# Boolean Indexing (Filter by Condition)
subset = my_series[my_series > 50]
# wq 123
# kl 90
# dtype: int64
# สร้าง Series ใหม่จาก Subset
new_series = my_series[['mn', 'az']].copy()
การจัดการ Index ที่ไม่มีอยู่
# ถ้า List มี Label ที่ไม่มีใน Series → KeyError
try:
my_series[['mn', 'xx']]
except KeyError as e:
print(f"Missing: {e}")
# ใช้ .loc กับ errors='ignore' (Pandas 1.5+)
# หรือ filter ก่อน
valid_labels = [l for l in ['mn', 'xx'] if l in my_series.index]
subset = my_series.loc[valid_labels]
Note: Double Brackets `[[...]]` สำคัญ - Single Bracket `['mn', 'az']` จะ Error (ถือเป็น Tuple Key)