DataFrame สามารถสร้างจาก Dictionary ที่ Value เป็น Series ได้ Key จะกลายเป็น Column Name และ Series Index จะกลายเป็น Row Index
ตัวอย่างโค้ด
import pandas as pd
my_data = {
'ab': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'mn': pd.Series([56, 78, 13, 13], index=['a', 'b', 'c', 'd'])
}
my_df = pd.DataFrame(my_data)
print("The dataframe created from dictionary of series:")
print(my_df)
ผลลัพธ์
The dataframe created from dictionary of series:
ab mn
a 1.0 56
b 2.0 78
c 3.0 13
d NaN 13
คำอธิบาย
Dictionary: Key = Column Name, Value = Series (มี Index ของตัวเอง)
DataFrame รวม Index ทั้งหมด (Union) → Index: a, b, c, d
Column 'ab' มีแค่ a,b,c → Index d ได้ NaN
Column 'mn' มี a,b,c,d → ค่าครบทุก Index
พฤติกรรม Index Alignment
| สถานการณ์ | ผลลัพธ์ |
|---|---|
| Series Index เหมือนกันทั้งหมด | DataFrame Index = Index นั้น |
| Series Index ต่างกัน | DataFrame Index = Union ของทุก Index (เรียง Sort) |
| Key ไม่มีใน Series บางตัว | NaN ที่ตำแหน่งที่ขาด |
วิธีสร้าง DataFrame อื่นๆ
# 1. Dictionary of Lists/Arrays (Index ต้องยาวเท่ากัน)
df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})
# 2. List of Dictionaries (แต่ละ Dict = 1 Row)
df = pd.DataFrame([{'A':1, 'B':4}, {'A':2, 'B':5}])
# 3. 2D Array / List of Lists
df = pd.DataFrame([[1,4], [2,5], [3,6]], columns=['A', 'B'])
# 4. NumPy Array
df = pd.DataFrame(np.array([[1,4], [2,5], [3,6]]), columns=['A', 'B'])
# 5. จาก File
df = pd.read_csv('data.csv')
การระบุ Index และ Columns ตอนสร้าง
df = pd.DataFrame(
data=my_data,
index=['a', 'b', 'c', 'd'], # บังคับ Index
columns=['ab', 'mn', 'new_col'] # บังคับ Columns (ใหม่จะได้ NaN)
)
Note: NaN = Not a Number แสดง Missing Value ใน Floating Point Columns