maxframe.dataframe.DataFrame.to_dict#

DataFrame.to_dict(orient='dict', into=<class 'dict'>, index=True, batch_size=10000, session=None)#

将 DataFrame 转换为字典。

键值对的类型可以通过参数自定义(见下文)。

参数:
  • orient (str {'dict', 'list', 'series', 'split', 'tight', 'records', 'index'}) -- 确定字典值的类型。 - 'dict'(默认): 类似 {column -> {index -> value}} 的字典 - 'list' : 类似 {column -> [values]} 的字典 - 'series' : 类似 {column -> Series(values)} 的字典 - 'split' : 类似 {'index' -> [index], 'columns' -> [columns], 'data' -> [values]} 的字典 - 'tight' : 类似 {'index' -> [index], 'columns' -> [columns], 'data' -> [values], 'index_names' -> [index.names], 'column_names' -> [column.names]} 的字典 - 'records' : 类似 [{column -> value}, ... , {column -> value}] 的列表 - 'index' : 类似 {index -> {column -> value}} 的字典

  • into (class, default dict) -- 返回值中所有映射使用的 collections.abc.MutableMapping 子类。可以是实际的类或你想要的映射类型的空实例。如果需要 collections.defaultdict,必须传入已初始化的对象。

  • index (bool, default True) -- 是否在返回的字典中包含索引项(如果 orient 是 'tight',还包括 index_names 项)。只有当 orient 是 'split' 或 'tight' 时才能为 False

返回:

返回表示 DataFrame 的 collections.abc.MutableMapping 对象。结果转换取决于 orient 参数。

返回类型:

dict, list or collections.abc.MutableMapping

参见

DataFrame.from_dict

从字典创建 DataFrame。

DataFrame.to_json

将 DataFrame 转换为 JSON 格式。

示例

>>> import maxframe.dataframe as md
>>> df = md.DataFrame({'col1': [1, 2],
...                    'col2': [0.5, 0.75]},
...                   index=['row1', 'row2'])
>>> df.execute()
      col1  col2
row1     1  0.50
row2     2  0.75
>>> df.to_dict()
{'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}

你可以指定返回的结构。

>>> df.to_dict('series')
{'col1': row1    1
         row2    2
Name: col1, dtype: int64,
'col2': row1    0.50
        row2    0.75
Name: col2, dtype: float64}
>>> df.to_dict('split')
{'index': ['row1', 'row2'], 'columns': ['col1', 'col2'],
 'data': [[1, 0.5], [2, 0.75]]}
>>> df.to_dict('records')
[{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]
>>> df.to_dict('index')
{'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}
>>> df.to_dict('tight')
{'index': ['row1', 'row2'], 'columns': ['col1', 'col2'],
 'data': [[1, 0.5], [2, 0.75]], 'index_names': [None], 'column_names': [None]}

你也可以指定映射类型。

>>> from collections import OrderedDict, defaultdict
>>> df.to_dict(into=OrderedDict)
OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2)])),
             ('col2', OrderedDict([('row1', 0.5), ('row2', 0.75)]))])

如果你想要一个 defaultdict,你需要先初始化它:

>>> dd = defaultdict(list)
>>> df.to_dict('records', into=dd)
[defaultdict(<class 'list'>, {'col1': 1, 'col2': 0.5}),
 defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]