您好,登錄后才能下訂單哦!
最近需要將csv文件轉(zhuǎn)成DataFrame并以json的形式展示到前臺,故需要用到Dataframe的to_json方法
to_json方法默認以列名為鍵,列內(nèi)容為值,形成{col1:[v11,v21,v31…],col2:[v12,v22,v32],…}這種格式,但有時我們需要按行來轉(zhuǎn)為json,形如這種格式[row1:{col1:v11,col2:v12,col3:v13…},row2:{col1:v21,col2:v22,col3:v23…}]
通過查找官網(wǎng)我們可以看到to_json方法有一個參數(shù)為orient,其參數(shù)說明如下:
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轉(zhuǎn)json,默認的orient是'index',orient可選參數(shù)有 {‘split','records','index'}
如果是DataFrame轉(zhuǎn)json,默認的orient是'columns',orient可選參數(shù)有 {‘split','records','index','columns','values'}
json的格式如下
split,樣式為 {index -> [index], columns -> [columns], data -> [values]}
records,樣式為[{column -> value}, … , {column -> value}]
index ,樣式為 {index -> {column -> value}}
columns,樣式為 {index -> {column -> value}}
values,數(shù)組樣式
table,樣式為{‘schema': {schema}, ‘data': {data}},和records類似
看一下官網(wǎng)給的demo
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"}]}'
主要參考官網(wǎng)API:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html
以上這篇pandas.DataFrame.to_json按行轉(zhuǎn)json的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。