maxframe.dataframe.DataFrame.from_dict#

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

从 array-like 或 dict 的字典构造 DataFrame。

通过列或索引从字典创建 DataFrame 对象,允许指定数据类型。

参数:
  • data (dict) -- 形式为 {field : array-like} 或 {field : dict}。

  • orient ({'columns', 'index', 'tight'}, default 'columns') -- 数据的“方向”。如果传入的字典的键应该是结果 DataFrame 的列,请传递 'columns'(默认)。如果键应该是行,请传递 'index'。如果为 'tight',则假定字典包含键 ['index', 'columns', 'data', 'index_names', 'column_names']。

  • dtype (dtype, default None) -- 在 DataFrame 构造后强制使用的数据类型,否则进行推断。

  • columns (list, default None) -- 当 orient='index' 时使用的列标签。如果与 orient='columns'orient='tight' 一起使用会引发 ValueError。

返回类型:

DataFrame

参见

DataFrame.from_records

从结构化 ndarray、元组或字典序列,或 DataFrame 构造 DataFrame。

DataFrame

使用构造函数创建 DataFrame 对象。

DataFrame.to_dict

将 DataFrame 转换为字典。

示例

默认情况下,字典的键将成为 DataFrame 的列:

>>> import maxframe.dataframe as md
>>> data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
>>> md.DataFrame.from_dict(data).execute()
   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']}
>>> md.DataFrame.from_dict(data, orient='index').execute()
       0  1  2  3
row_1  3  2  1  0
row_2  a  b  c  d

使用 'index' 方向时,可以手动指定列名:

>>> md.DataFrame.from_dict(data, orient='index',
...                        columns=['A', 'B', 'C', 'D']).execute()
       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']}
>>> md.DataFrame.from_dict(data, orient='tight').execute()
z1     x  y
z2     1  2
n1 n2
a  b   1  3
   c   2  4