python: pandas to_json官方文档及实例
时间格式参数:(timestamp)
# 单位:秒,格式: ISO8601(大写)
df = df.to_json(orient="records", date_format = 'ISO8601', date_unit = 's')
官方文档:
date_format{None, ‘epoch’, ‘iso’}
Type of date conversion. ‘epoch’ = epoch milliseconds, ‘iso’ = ISO8601. The default depends on the orient. For orient='table', the default is ‘iso’. For all other orients, the default is ‘epoch’.
date_unitstr, default ‘ms’ (milliseconds)
The time unit to encode to, governs timestamp and ISO8601 precision. One of ‘s’, ‘ms’, ‘us’, ‘ns’ for second, millisecond, microsecond, and nanosecond respectively.
DataFrame转换为json的格式类型参数:orient
orient : str
Indication of expected JSON string format.
Series:
default is ‘index’
allowed values are: {‘split’,’records’,’index’,’table’}.
DataFrame:
default is ‘columns’
allowed values are: {‘split’, ‘records’, ‘index’, ‘columns’, ‘values’, ‘table’}.
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, where data component is like orient='records'.
Changed in version 0.20.0.
For example:
import pandas as pd
df = pd.DataFrame({'name':['tian','ning'], 'age':[19,20]})
"""python
name age
0 tian 19
1 ning 20
"""
columns
df.to_json(orient='columns')
# {"name":{"0":"tian","1":"ning"},"age":{"0":19,"1":20}}
"""
{
"name":{
"0":"tian",
"1":"ning"
},
"age":{
"0":19,
"1":20
}
}
"""
table
df.to_json(orient='table')
# {"schema":{"fields":[{"name":"index","type":"integer"},{"name":"name","type":"string"},{"name":"age","type":"integer"}],"primaryKey":["index"],"pandas_version":"0.20.0"},"data":[{"index":0,"name":"tian","age":19},{"index":1,"name":"ning","age":20}]}
"""
{
"schema":{
"fields":[
{
"name":"index",
"type":"integer"
},
{
"name":"name",
"type":"string"
},
{
"name":"age",
"type":"integer"
}
],
"primaryKey":[
"index"
],
"pandas_version":"0.20.0"
},
"data":[
{
"index":0,
"name":"tian",
"age":19
},
{
"index":1,
"name":"ning",
"age":20
}
]
}
"""
index
df.to_json(orient='index')
# {"0":{"name":"tian","age":19},"1":{"name":"ning","age":20}}
"""
{
"0":{
"name":"tian",
"age":19
},
"1":{
"name":"ning",
"age":20
}
}
"""
values
df.to_json(orient='values')
# [["tian",19],["ning",20]]
"""
[
[
"tian",
19
],
[
"ning",
20
]
]
"""
split
df.to_json(orient='split')
# {"columns":["name","age"],"index":[0,1],"data":[["tian",19],["ning",20]]}
"""
{
"columns":[
"name",
"age"
],
"index":[
0,
1
],
"data":[
[
"tian",
19
],
[
"ning",
20
]
]
}
"""
records
df.to_json(orient='records')
# [{"name":"tian","age":19},{"name":"ning","age":20}]
"""
[
{
"name":"tian",
"age":19
},
{
"name":"ning",
"age":20
}
]
"""
