pandas中dataframe转字典df.to_dict('records')
有这么一个需求,pandas用dataframe处理了数据,转成dict,再用json输出到http.
DataFrame.
to_dict
(orient='dict', into=
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
You can specify the return orientation.
You can also specify the mapping type.
If you want a defaultdict, you need to initialize it: