One - One Code All

Blog Content

pandas中dataframe转字典df.to_dict('records')

Python 统计学-科学计算   2014-01-04 21:30:03

pandas中dataframe转字典df.to_dict('records')


有这么一个需求,pandas用dataframe处理了数据,转成dict,再用json输出到http.


  • DataFrame.to_dict(orient='dict'into=)[source]

  • Convert the DataFrame to a dictionary.

    The type of the key-value pairs can be customized with the parameters (see below).

    Parameters:
    Returns:
    • dict, list or collections.Mapping

    • Return a collections.Mapping object representing the DataFrame. The resulting transformation depends on the orient parameter.


    • ‘dict’ (default) : dict like {column -> {index -> value}}

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

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

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

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

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

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

    • Determines the type of the values of the dictionary.

      Abbreviations are allowed. s indicates series and sp indicates split.

    • into : class, default dict

    • The collections.Mapping subclass used for all Mappings in the return value. Can be the actual class or an empty instance of the mapping type you want. If you want a collections.defaultdict, you must pass it initialized.

      New in version 0.21.0.



Examples

>>> df = pd.DataFrame({'col1': [1, 2],...                    'col2': [0.5, 0.75]},...                   index=['row1', 'row2'])>>> df      col1  col2row1     1  0.50row2     2  0.75>>> df.to_dict(){'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}

You can specify the return orientation.

>>> df.to_dict('series'){'col1': row1    1         row2    2Name: col1, dtype: int64,'col2': row1    0.50        row2    0.75Name: 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}}

You can also specify the mapping type.

>>> 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(, {'col1': 1, 'col2': 0.5}), defaultdict(, {'col1': 2, 'col2': 0.75})]



上一篇:python有限状态机transitions
下一篇:airflow之DAGs详解

The minute you think of giving up, think of the reason why you held on so long.