วิธีแปลงพจนานุกรมเป็น pandas dataframe (2 ตัวอย่าง)
คุณสามารถใช้วิธีใดๆ ต่อไปนี้เพื่อแปลงพจนานุกรมใน Python เป็น Pandas DataFrame:
วิธีที่ 1: ใช้ dict.items()
df = pd. DataFrame (list(some_dict. items ()), columns = [' col1 ', ' col2 '])
วิธีที่ 2: ใช้ from_dict()
df = pd. DataFrame . from_dict (some_dict, orient=' index '). reset_index () df. columns = [' col1 ', ' col2 ']
ทั้งสองวิธีให้ผลลัพธ์ที่เหมือนกัน
ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีในทางปฏิบัติ
ตัวอย่างที่ 1: แปลงพจนานุกรมเป็น DataFrame โดยใช้ dict.items()
สมมติว่าเรามีพจนานุกรมต่อไปนี้ใน Python:
#create dictionary
some_dict = {'Lebron':26,'Luka':30,'Steph':22,'Nicola':29, 'Giannis':31}
เราสามารถใช้รหัสต่อไปนี้เพื่อแปลงพจนานุกรมนี้เป็น DataFrame ของแพนด้า:
import pandas as pd #convert dictionary to pandas DataFrame df = pd. DataFrame (list(some_dict. items ()), columns = [' Player ', ' Points ']) #view DataFrame df Player Points 0 Lebron 26 1 Luke 30 2 Steph 22 3 Nicola 29 4 Giannis 31
นอกจากนี้เรายังสามารถใช้ฟังก์ชัน type() เพื่อยืนยันว่าผลลัพธ์เป็น pandas DataFrame:
#display type of df
type(df)
pandas.core.frame.DataFrame
ตัวอย่างที่ 2: แปลงพจนานุกรมเป็น DataFrame โดยใช้ from_dict()
สมมติว่าเรามีพจนานุกรมต่อไปนี้ใน Python:
#create dictionary
some_dict = {'Lebron':26,'Luka':30,'Steph':22,'Nicola':29, 'Giannis':31}
เราสามารถใช้รหัสต่อไปนี้เพื่อแปลงพจนานุกรมนี้เป็น DataFrame ของแพนด้า:
import pandas as pd #convert dictionary to pandas DataFrame df = pd. DataFrame . from_dict (some_dict, orient=' index '). reset_index () #define column names of DataFrame df.columns = [' Player ', ' Points '] #view DataFrame df Player Points 0 Lebron 26 1 Luke 30 2 Steph 22 3 Nicola 29 4 Giannis 31
นอกจากนี้เรายังสามารถใช้ฟังก์ชัน type() เพื่อยืนยันว่าผลลัพธ์เป็น pandas DataFrame:
#display type of df
type(df)
pandas.core.frame.DataFrame
โปรดทราบว่าวิธีนี้ให้ผลลัพธ์เหมือนกับวิธีก่อนหน้าทุกประการ
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำงานทั่วไปอื่นๆ ในแพนด้า:
วิธีแปลง Pandas DataFrame เป็นพจนานุกรม
วิธีแปลง Pandas PivotTable เป็น DataFrame
วิธีแปลงเอาต์พุต Pandas GroupBy เป็น DataFrame