pandas 中 to_dict 的用法

【時間】2019.11.16

【題目】pandas 中 to_dict 的用法

 轉自:pandas 中 to_dict 的用法

一、語法

DataFrame.to_dict(orient='dict', into=<class 'dict'>)
參數:

orient : str {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}

 

  • ‘dict’ (default) : {column -> {index -> value}}
  • ‘list’ :  {column -> [values]}
  • ‘series’ : {column -> Series(values)}
  • ‘split’ : {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
  • ‘records’ : [{column -> value}, … , {column -> value}]
  • ‘index’ : {index -> {column -> value}}

也可以用縮寫表示,  s 代表 series ,sp 代表 split.

into : class, 默認dict

Returns:

dict, list 或 collections.Mapping

 

二、例子

1、orient默認爲dict,返回每一列數據,字典的字典。

>>> 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}}

2、orient='series',返回每一列數據(<class 'pandas.core.series.Series'>),字典表示。

>>> df.to_dict('series')
{'col1': row1    1
         row2    2
Name: col1, dtype: int64,
'col2': row1    0.50
        row2    0.75
Name: col2, dtype: float64}

3、orient='split':列名稱(columns)、行名稱(index)、data分離

>>> df.to_dict('split')
{'index': ['row1', 'row2'], 'columns': ['col1', 'col2'],
 'data': [[1, 0.5], [2, 0.75]]}

4、orient='record':返回每一行數據(記錄)的列表

>>> df.to_dict('records')
[{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]

5、orient='series':在orient='record'基礎上加上行index,返回每一行數據(記錄)的字典

>>> df.to_dict('index')
{'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}

6、OrderedDict, defaultdict

>>> 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)]))])

If you want a defaultdict, you need to initialize it:

>>> 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})]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章