DataFrame สามารถสร้างจาก List of Dictionaries ได้ โดยแต่ละ Dictionary = 1 Row, Keys = Column Names
ตัวอย่างโค้ด
import pandas as pd
my_data = [
{'ab': 34},
{'mn': 56},
{'gh': 78},
{'wq': 90},
{'az': 123},
{'kl': 45}
]
my_df = pd.DataFrame(my_data)
print("The dataframe created from list of dictionary:")
print(my_df)
ผลลัพธ์
The dataframe created from list of dictionary:
ab az gh kl mn wq
0 34.0 NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN 56.0 NaN
2 NaN NaN 78.0 NaN NaN NaN
3 NaN NaN NaN NaN NaN 90.0
4 NaN 123.0 NaN NaN NaN NaN
5 NaN NaN NaN 45.0 NaN NaN
คำอธิบาย
List of Dicts: แต่ละ Dict มี Key ต่างกัน (Key เดียวต่อ Dict)
DataFrame รวม Keys ทั้งหมดเป็น Columns (ab, az, gh, kl, mn, wq)
แต่ละ Row มีค่าเพียง 1 Column ที่มีข้อมูล ที่เหลือเป็น NaN
กรณีทั่วไป: List of Dicts ที่มี Keys เหมือนกัน (แต่ละ Row ครบ)
# Typical: Records จาก Database/API
data = [
{'name': 'Tom', 'age': 45, 'city': 'Bangkok'},
{'name': 'Jane', 'age': 32, 'city': 'Chiang Mai'},
{'name': 'Bob', 'age': 28, 'city': 'Phuket'}
]
df = pd.DataFrame(data)
print(df)
# name age city
# 0 Tom 45 Bangkok
# 1 Jane 32 Chiang Mai
# 2 Bob 28 Phuket
การระบุ Columns และ Index
# บังคับ Columns (เรียงลำดับ, เพิ่ม Column ใหม่ได้)
df = pd.DataFrame(data, columns=['name', 'age', 'city', 'country'])
# country จะเป็น NaT/NaN ทั้งหมด
# บังคับ Index
df = pd.DataFrame(data, index=['row1', 'row2', 'row3'])
จาก List of Dicts → DataFrame → Dict/Records
# DataFrame → List of Dicts (Records)
records = df.to_dict('records')
# [{'name': 'Tom', 'age': 45, 'city': 'Bangkok'}, ...]
# DataFrame → Dict of Lists
dict_lists = df.to_dict('list')
# {'name': ['Tom', 'Jane', 'Bob'], 'age': [45, 32, 28], ...}
# DataFrame → Dict of Series
dict_series = df.to_dict('series')
สรุป: โครงสร้าง Input ต่างๆ สำหรับ DataFrame
| Input Structure | Key→Column? | แต่ละ Item = | ใช้เมื่อไหร่ |
|---|---|---|---|
| Dict of Series/Lists | Key = Col | Column | ข้อมูล Column-wise |
| List of Dicts | Key = Col | Row | Records, JSON, API Response |
| 2D Array/List of Lists | ต้องระบุ columns | Row | Matrix, NumPy Array |
| NumPy Structured Array | Field = Col | Row | Structured Data |