Pandas Series สามารถสร้างจาก Dictionary ได้โดย Key จะกลายเป็น Index และ Value จะกลายเป็น Data ยังสามารถกำหนด Index เองได้อีกด้วย
ตัวอย่าง 1: สร้างจาก Dictionary พร้อม Index ตรงกับ Key
import pandas as pd
my_data = {'ab': 11., 'mn': 15., 'gh': 28., 'kl': 45.}
my_index = ['ab', 'mn', 'gh', 'kl']
my_series = pd.Series(my_data, index=my_index)
print("Series from dict with matching index:")
print(my_series)
ผลลัพธ์
Series from dict with matching index:
ab 11.0
mn 15.0
gh 28.0
kl 45.0
dtype: float64
ตัวอย่าง 2: Index มีค่ามากกว่า Dictionary
my_data = {'ab': 11., 'mn': 15., 'gh': 28., 'kl': 45.}
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)
print("Series with extra index values:")
print(my_series)
ผลลัพธ์
Series with extra index values:
ab 11.0
mn 15.0
gh 28.0
kl 45.0
wq NaN
az NaN
dtype: float64
คำอธิบาย
สร้าง Dictionary {key: value}
กำหนด Index List (อาจตรงกับ Key หรือมีมากกว่า/น้อยกว่า)
สร้าง Series:
pd.Series(data, index=index_list)Index ที่มีใน Dictionary จะได้ Value ตรงกัน
Index ที่ไม่มีใน Dictionary จะได้ NaN (Not a Number)
พฤติกรรม Index ต่างๆ
| สถานการณ์ | ผลลัพธ์ |
|---|---|
| Index ⊂ Dict Keys | ดึงเฉพาะ Key ที่อยู่ใน Index |
| Index = Dict Keys | ลำดับตาม Index ที่กำหนด |
| Index ⊃ Dict Keys | Key เพิ่มเติมได้ NaN |
| ไม่ระบุ Index | ใช้ Dict Keys เรียงตามลำดับ Insertion (Python 3.7+) |
ตัวอย่างเพิ่มเติม: Index น้อยกว่า Dictionary
my_data = {'ab': 11., 'mn': 15., 'gh': 28., 'kl': 45.}
my_index = ['ab', 'mn']
my_series = pd.Series(my_data, index=my_index)
print(my_series)
# ab 11.0
# mn 15.0
# dtype: float64
สรุป: Index เป็นตัวควบคุมลำดับและเลือกว่าจะเอา Key ไหนจาก Dictionary มาใส่ใน Series