pandas.DataFrame.to_dict#
- DataFrame.to_dict(orient='dict', into=<class 'dict'>)[源代码]#
将DataFrame转换为词典。
键-值对的类型可以通过参数进行定制(如下所示)。
- 参数
- orientStr{‘dict’,‘List’,‘Series’,‘Split’,‘Record’,‘index’}
确定词典的值的类型。
‘dict’(默认):Dict Like{Column->{index->Value}}
‘list’:Dict Like{Column-> [值] }
‘Series’:Dict Like{Column->Series(Values)}
‘Split’:Dict Like{‘index’-> [索引] ,‘列’-> [列] ,‘数据’-> [值] }
‘tack’:Dict Like{‘index’-> [索引] ,‘列’-> [列] ,‘数据’-> [值] ,‘INDEX_NAMES’-> [index.names] ,‘Column_Names’-> [column.names] }
《唱片》:列表如下 [{{column -> value}}, ... , {{column -> value}}]
‘index’:字典Like{index->{Column->Value}}
允许使用缩写。 s 表示 series 和 sp 表示 split 。
1.4.0 新版功能: 属性的允许值为“Tack”
orient
论据- into类,默认字典
用于返回值中所有映射的集合.abc.Maping子类。可以是所需映射类型的实际类或空实例。如果您想要一个Collection tions.defaultdict,则必须将其初始化。
- 退货
- 词典、列表或集合。abc映射
返回一个表示DataFrame的集合.abc.map对象。所产生的转换取决于 orient 参数。
参见
DataFrame.from_dict
从词典创建DataFrame。
DataFrame.to_json
将DataFrame转换为JSON格式。
示例
>>> 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})]