當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python pandas.DataFrame.from_dict用法及代碼示例

用法:

classmethod DataFrame.from_dict(data, orient='columns', dtype=None, columns=None)

從 array-like 的字典或字典構造 DataFrame。

通過列或索引從字典創建 DataFrame 對象,允許 dtype 規範。

參數

datadict

形式為 {field: array-like} 或 {field: dict}。

orient{‘columns’, ‘index’, ‘tight’},默認 ‘columns’

數據的“orientation”。如果傳遞的 dict 的鍵應該是結果 DataFrame 的列,則傳遞‘columns’(默認)。否則,如果鍵應該是行,則傳遞‘index’。如果‘tight’,假設一個帶有鍵[‘index’, ‘columns’, ‘data’,‘index_names’, ‘column_names’]的字典。

dtypedtype,默認無

要強製的數據類型,否則推斷。

columns列表,默認無

orient='index' 時使用的列標簽。如果與 orient='columns'orient='tight' 一起使用,則會引發 ValueError。

返回

DataFrame

例子

默認情況下,dict 的鍵成為 DataFrame 列:

>>> data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
>>> pd.DataFrame.from_dict(data)
   col_1 col_2
0      3     a
1      2     b
2      1     c
3      0     d

指定 orient='index' 以使用字典鍵作為行來創建 DataFrame:

>>> data = {'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']}
>>> pd.DataFrame.from_dict(data, orient='index')
       0  1  2  3
row_1  3  2  1  0
row_2  a  b  c  d

使用‘index’ 方向時,可以手動指定列名:

>>> pd.DataFrame.from_dict(data, orient='index',
...                        columns=['A', 'B', 'C', 'D'])
       A  B  C  D
row_1  3  2  1  0
row_2  a  b  c  d

指定 orient='tight' 以使用 ‘tight’ 格式創建 DataFrame:

>>> data = {'index': [('a', 'b'), ('a', 'c')],
...         'columns': [('x', 1), ('y', 2)],
...         'data': [[1, 3], [2, 4]],
...         'index_names': ['n1', 'n2'],
...         'column_names': ['z1', 'z2']}
>>> pd.DataFrame.from_dict(data, orient='tight')
z1     x  y
z2     1  2
n1 n2
a  b   1  3
   c   2  4

相關用法


注:本文由純淨天空篩選整理自pandas.pydata.org大神的英文原創作品 pandas.DataFrame.from_dict。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。