pandas.DataFrame.to_json按行转json的方法
本文介绍如何使用pandas.DataFrame.to_json方法将数据框转换为JSON格式。重点讲解orient参数,特别是records选项如何实现按行转换,生成[{column -> value}, ...]格式的列表,适用于前端展示等场景。
近期工作中遇到需求,需将CSV文件读取为DataFrame,并以JSON格式输出至前端展示,因此涉及使用DataFrame的to_json方法。
to_json方法默认以列名为键、列内容为值,生成类似{col1:[v11,v21,v31…],col2:[v12,v22,v32],…}的结构。但有时需要按行转换为JSON,格式如[row1:{col1:v11,col2:v12,col3:v13…},row2:{col1:v21,col2:v22,col3:v23…}]。
查阅官方文档可知,to_json方法包含orient参数,其说明如下:
orient : string
Series
default is ‘index'
allowed values are: {‘split','records','index'}
DataFrame
default is ‘columns'
allowed values are: {‘split','records','index','columns','values'}
The format of the JSON string
split : dict like {index -> [index], columns -> [columns], data -> [values]}
records : list like [{column -> value}, … , {column -> value}]
index : dict like {index -> {column -> value}}
columns : dict like {column -> {index -> value}}
values : just the values array
table : dict like {‘schema': {schema}, ‘data': {data}} describing the data, and the data component is like orient='records'.
Changed in version 0.20.0
具体含义为:
若对Series进行JSON转换,默认orient为'index',可选参数包括{‘split','records','index'}。
若对DataFrame进行JSON转换,默认orient为'columns',可选参数包括{‘split','records','index','columns','values'}。
各orient参数对应的JSON格式如下:
split格式为{index -> [index], columns -> [columns], data -> [values]}。
records格式为[{column -> value}, … , {column -> value}]。
index格式为{index -> {column -> value}}。
columns格式为{column -> {index -> value}}。
values仅输出值数组。
table格式为{‘schema': {schema}, ‘data': {data}},与records类似。
参考官方示例:
df = pd.DataFrame([['a', 'b'], ['c', 'd']],
index=['row 1', 'row 2'],
columns=['col 1', 'col 2'])
###########
split
###########
df.to_json(orient='split')
>'{"columns":["col 1","col 2"],
"index":["row 1","row 2"],
"data":[["a","b"],["c","d"]]}'
###########
index
###########
df.to_json(orient='index')
>'{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
###########
records
###########
df.to_json(orient='index')
>'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
###########
table
###########
df.to_json(orient='table')
>'{"schema": {"fields": [{"name": "index", "type": "string"},
{"name": "col 1", "type": "string"},
{"name": "col 2", "type": "string"}],
"primaryKey": "index",
"pandas_version": "0.20.0"},
"data": [{"index": "row 1", "col 1": "a", "col 2": "b"},
{"index": "row 2", "col 1": "c", "col 2": "d"}]}'
主要参考官方API文档:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html
以上即为pandas.DataFrame.to_json按行转换JSON的方法分享,希望提供有用参考,欢迎支持。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













