ในการแปลง Pandas DataFrame เป็นพจนานุกรม เราสามารถใช้เมธอด to_dict() มาดูตัวอย่างกันและดูว่ามันทำอย่างไร
ขั้นตอน
- สร้างข้อมูลตารางแบบสองมิติ ปรับขนาดได้ และอาจต่างกันได้ df .
- พิมพ์ DataFrame อินพุต df .
- แปลง DataFrame เป็นพจนานุกรมโดยใช้ to_dict() วิธีการและพิมพ์ออกมา
ตัวอย่าง
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print "Input DataFrame is:\n", df
print "Convert DataFrame into dictionary: \n", df.to_dict() ผลลัพธ์
Input DataFrame is:
x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1
Convert DataFrame into dictionary:
{'x': {0: 5, 1: 2, 2: 7, 3: 0}, 'y': {0: 4, 1: 7, 2: 5, 3: 1},
'z': {0: 9, 1: 3, 2: 5, 3: 1}}