pd.DataFrame.from_dict()方法用於將Dict轉換為DataFrame對象。 此方法接受以下參數。
-
[ data] :字典或類似數組的對象,用來創建DataFrame。
-
[orient] :數據的方向。 允許值為(“列”,“索引”),默認值為“列”。
-
[columns ] :當方向為“索引”時,用作DataFrame標簽的值的列表。 如果與列方向一起使用,則會引發ValueError 。
示例:
1. 從Dict創建DataFrame的簡單示例 (Simple Example to create DataFrame from Dict)
點擊查看代碼
import pandas as pd
d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}
df = pd.DataFrame.from_dict(d1)
df
Output:

2. 從具有索引方向的Dict創建DataFrame (Creating DataFrame from Dict with index orientation)
點擊查看代碼
### 指定 orient='index'
import pandas as pd
d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}
df = pd.DataFrame.from_dict(d1, orient='index')
df

3. 將具有索引方向的Dict轉換為Dict時,將標簽分配給DataFrame列 (Assigning Labels to DataFrame Columns when converted Dict with index orientation)
點擊查看代碼
import pandas as pd
d1 = {'Name': ['Pankaj', 'Meghna'], 'ID': [1, 2], 'Role': ['CEO', 'CTO']}
df = pd.DataFrame.from_dict(d1, columns=['A', 'B'], orient='index')
df
Output:

我們也可以使用其構造函數將字典轉換為DataFrame,但是,沒有選擇使用基於索引的方向。
點擊查看代碼
import pandas as pd
d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}
df = pd.DataFrame(d1)
df
Output:

