[央视热点] dataframe.to_json()中orient 参数详解[百度新闻]

[央视热点] dataframe.to_json()中orient 参数详解[百度新闻]

已邀请:
Pandas DataFrame 有一个方法 dataframe.to_json(),它可以将 DataFrame 转换为 JSON 字符串或存储为外部 JSON 文件。最终的 JSON 格式取决于 orient 参数的值,默认情况下是'columns,但也可以指定为'records'、'index'、'split'、'table'和'values'。
1.orient = 'columns'
import pandas as pd

df = pd.DataFrame([['Jay',16,'BBA'],
['Jack',19,'BTech'],
['Mark',18,'BSc']],
columns = ['Name','Age','Course'])

js = df.to_json(orient = 'columns')

print(js)
输出:

{"Name":{"0":"Jay","1":"Jack","2":"Mark"},
"Age":{"0":16,"1":19,"2":18},
"Course":{"0":"BBA","1":"BTech","2":"BSc"}}
2.orient = 'records'
import pandas as pd

df = pd.DataFrame([['Jay',16,'BBA'],
['Jack',19,'BTech'],
['Mark',18,'BSc']],
columns = ['Name','Age','Course'])

js = df.to_json(orient = 'records')

print(js)
输出:

[{"Name":"Jay","Age":16,"Course":"BBA"},{"Name":"Jack","Age":19,"Course":"BTech"},{"Name":"Mark","Age":18,"Course":"BSc"}]
3.orient = 'index'
import pandas as pd

df = pd.DataFrame([['Jay',16,'BBA'],
['Jack',19,'BTech'],
['Mark',18,'BSc']],
columns = ['Name','Age','Course'])

js = df.to_json(orient = 'index')

print(js)
输出:

{"0":{"Name":"Jay","Age":16,"Course":"BBA"},
"1":{"Name":"Jack","Age":19,"Course":"BTech"},
"2":{"Name":"Mark","Age":18,"Course":"BSc"}}
4.orient = 'split'
import pandas as pd

df = pd.DataFrame([['Jay',16,'BBA'],
['Jack',19,'BTech'],
['Mark',18,'BSc']],
columns = ['Name','Age','Course'])

js = df.to_json(orient = 'split')

print(js)
输出:

{"columns":["Name","Age","Course"],
"index":[0,1,2],
"data":[["Jay",16,"BBA"],["Jack",19,"BTech"],["Mark",18,"BSc"]]}
5.orient = 'table'
import pandas as pd

df = pd.DataFrame([['Jay',16,'BBA'],
['Jack',19,'BTech'],
['Mark',18,'BSc']],
columns = ['Name','Age','Course'])

js = df.to_json(orient = 'table')

print(js)
输出:

{"schema": {"fields":[{"name":"index","type":"integer"},{"name":"Name","type":"string"},{"name":"Age","type":"integer"},{"name":"Course","type":"string"}],"primaryKey":["index"],"pandas_version":"0.20.0"}, "data": [{"index":0,"Name":"Jay","Age":16,"Course":"BBA"},{"index":1,"Name":"Jack","Age":19,"Course":"BTech"},{"index":2,"Name":"Mark","Age":18,"Course":"BSc"}]}

如前所述,我们还可以直接将 JSON 输出到外部文件。它可以通过在 dataframe.to_json() 函数中提供文件的路径来实现,如下所示。

import pandas as pd

df = pd.DataFrame([['Jay',16,'BBA'],
['Jack',19,'BTech'],
['Mark',18,'BSc']], columns = ['Name','Age','Course'])

df.to_json("path\example.json", orient = 'table')

要回复问题请先登录注册