pandas.DataFrame.to_dict#

DataFrame.to_dict(orient='dict', *, into=<class 'dict'>, index=True)[源代码]#

将 DataFrame 转换为字典。

键值对的类型可以通过参数(如下所示)进行自定义。

Parameters:
orientstr {‘dict’, ‘list’, ‘series’, ‘split’, ‘tight’, ‘records’, ‘index’}

确定字典值的类型。

  • ‘dict’ (默认) : dict 类似 {column -> {index -> value}}

  • ‘list’ : dict 类似 {column -> [values]}

  • ‘series’ : dict 类似 {column -> Series(values)}

  • ‘split’ : dict 类似 {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}

  • ‘tight’ : dict 类似 {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values], ‘index_names’ -> [index.names], ‘column_names’ -> [column.names]}

  • ‘records’ : list 类似 [{column -> value}, … , {column -> value}]

  • ‘index’ : dict 类似 {index -> {column -> value}}

在 1.4.0 版本加入: ‘tight’ as an allowed value for the orient argument

intoclass, 默认为 dict

返回的所有 Mapping 中使用的 collections.abc.MutableMapping 子类。可以是实际的类,也可以是您想要的映射类型的空实例。如果要使用 collections.defaultdict,必须先初始化它。

indexbool, default True

是否在返回的字典中包含索引项(如果 orient 为 ‘tight’,则还包括 index_names 项)。当 orient 为 ‘split’ 或 ‘tight’ 时,只能为 False

在 2.0.0 版本加入.

Returns:
dict, list 或 collections.abc.MutableMapping

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

参见

DataFrame.from_dict

从字典创建 DataFrame。

DataFrame.to_json

将 DataFrame 转换为 JSON 格式。

Examples

>>> df = pd.DataFrame({'col1': [1, 2],
...                    'col2': [0.5, 0.75]},
...                   index=['row1', 'row2'])
>>> df
      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})]