Pandas DataFrame.to_json(~) 方法将 DataFrame 转换为 JSON 字符串,或输出 JSON 文件。
参数
1.path_or_buf | string 或 file handle | optional
您要保存 JSON 的路径。默认情况下,该方法将返回 JSON 字符串,而不写入文件。
2. orient | string
您希望如何将源 DataFrame 转换为 JSON。
对于"split":
{
   "index": [list of index],
   "columns": [list of labels],
   "data": [list of values]
}对于"records":
[{column_label: values}, ... , {column_label: values}]在这里,我们将每个项目称为记录.
对于"index":
{
   index:
      column_label: value
      ...
   index:
      ...
}对于"columns"(默认):
{
   column_label:
      index: value
      ...
   column_label:
      ...
}对于 "values" ,我们只得到一个值列表:
[value_one, ..., ]对于 "table" ,我们得到源 DataFrame 的全面表示:
{
   "schema": {schema}
   "data": {data}
}默认情况下,orient="columns" 。
3. date_format | string | optional
是否将日期转换为纪元毫秒或 iso8601 格式。允许值如下:
- 
"epoch":自1970-01-01以来经过的时间(以毫秒为单位)。
- 
"iso":日期表示的全局标准。
默认情况下,如果 orient="table" ,则 date_format="iso" ,否则 "epoch" 。
4. double_precision | int | optional
存储浮点数的小数位数。默认情况下,double_precision=10 。
5. force_ascii | boolean | optional
是否使用 ASCII 来编码字符串。默认情况下,force_ascii=True 。
6. date_unit | string | optional
要使用的时间单位。允许的值如下:
- 
"s":秒
- 
"ms":毫秒
- 
"us":微秒
- 
"ns":纳秒
默认情况下,date_unit="ms" 。
7. default_handler | callable | optional
JSON 转换不成功时触发的回调。回调将源 DataFrame 作为参数并返回可序列化的对象(例如映射和列表)。默认情况下,default_handler=None 。
8. lines | boolean | optional
如果是orient="records",则在新行中写出每个{column_label:values}。传入 True 作为 "records" 以外的值将导致错误。默认情况下,lines=False 。
9. compression | string | optional
输出到文件时使用的压缩算法。可用的算法有:
"infer", "gzip", "bz2", "zip", "xz"这仅在我们输出到文件时才相关,即指定了path_or_buf。默认情况下,compression="infer" 。
10.index | boolean | optional
是否在生成的 JSON 字符串中包含索引。仅当 orient 是 "split" 或 "table" 时才相关。默认情况下,index=True 。
11.indent | int | optional
每条记录缩进的空格数。
返回值
如果指定path_or_buf,则返回None。否则,返回 JSON 格式的string。
例子
输出到文件
考虑以下 DataFrame :
df = pd.DataFrame({"A":[2,3], "B":[4,5]}, index=["a","b"])
df
   A  B
a  2  4
b  3  5我们可以通过传入 path_or_buf 将 JSON 输出到文件,而不是获取 JSON 字符串,如下所示:
df.to_json(path_or_buf="my_json")这将在与 Python 脚本相同的目录中创建一个名为 my_json 的新文件:
{"A":{"a":2,"b":3},"B":{"a":4,"b":5}}指定方向
考虑以下 DataFrame :
df = pd.DataFrame({"A":[2,3], "B":[4,5]}, index=["a","b"])
df
   A  B
a  2  4
b  3  5默认
默认情况下,orient="columns":
df.to_json()
'{"A":{"a":2,"b":3},"B":{"a":4,"b":5}}'分裂
df.to_json(orient="split")
'{"columns":["A","B"],"index":["a","b"],"data":[[2,4],[3,5]]}'记录
df.to_json(orient="records")
'[{"A":2,"B":4},{"A":3,"B":5}]'index
df.to_json(orient="index")
'{"a":{"A":2,"B":4},"b":{"A":3,"B":5}}'列
df.to_json(orient="columns")
'{"A":{"a":2,"b":3},"B":{"a":4,"b":5}}'值
df.to_json(orient="values")
'[[2,4],[3,5]]'表格
df.to_json(orient="table")
'{"schema":{"fields":[{"name":"index","type":"string"},
                      {"name":"A","type":"integer"},
                      {"name":"B","type":"integer"}],
            "primaryKey":["index"],
            "pandas_version":"0.20.0"}
  "data":[{"index":"a","A":2,"B":4},
          {"index":"b","A":3,"B":5}]}'在这里,为了清晰起见,我们对输出进行了美化,但实际输出全部在一行中。
指定date_format
考虑以下 DataFrame :
df = pd.DataFrame({"A":["2020-12-25"], "B":["2020-12-20"]}, dtype="datetime64[ns]")
df
   A           B
0  2020-12-25  2020-12-20默认情况下, date_format="epoch" (除非 orient="table" ):
df.to_json()    # date_format="epoch"
'{"A":{"0":1608854400000},"B":{"0":1608422400000}}'这里,大数字表示自 1970-01-01 以来经过的时间(以毫秒为单位)。
另一方面,我们可以通过传入 "iso" 将日期格式更改为 iso8601,如下所示:
df.to_json(date_format="iso")
'{"A":{"0":"2020-12-25T00:00:00.000Z"},"B":{"0":"2020-12-20T00:00:00.000Z"}}'指定date_unit
考虑以下 DataFrame :
df = pd.DataFrame({"A":["2020-12-25"], "B":["2020-12-20"]}, dtype="datetime64[ns]")
df
   A           B
0  2020-12-25  2020-12-20默认情况下,当 date_format="epoch" 时,单位为毫秒:
df.to_json()    # date_format="epoch"
'{"A":{"0":1608854400000},"B":{"0":1608422400000}}'这里,大数字表示自 1970-01-01 以来经过的时间(以毫秒为单位)。
我们可以将单位更改为秒,如下所示:
df.to_json(date_unit="s")    # date_format="epoch"
'{"A":{"0":1608854400},"B":{"0":1608422400}}'指定default_handler
考虑以下 DataFrame :
df = pd.DataFrame({"A":[complex(3,4)], "B":[4]}, index=["a"])
df
   A                   B
a  3.000000+4.000000j  4这里,我们的df有一个复数。
默认情况下,当我们尝试将 df 转换为 JSON 字符串时,我们会得到以下结果:
df.to_json(orient="records")
'[{"A":{"imag":4.0},"B":4}]'请注意复数如何错误地表示为 "imag" ,这是因为 JSON 不知道如何在内部解析复数。对于像这样转换不正确的情况,我们可以使用default_handler参数来控制返回的内容:
def my_handler(my_df):
    return pd.DataFrame({"A":[3], "B":[4]}, index=["a"])
df.to_json(orient="records", default_handler=my_handler)
'[{"A":[{"A":3,"B":4}],"B":4}]'该处理程序将源 DataFrame 作为参数,并返回一个可序列化的对象,如Map、Series、DataFrame 等。现在,我们可以返回我们喜欢的另一个 JSON,而不是之前的格式错误的 JSON。
指定线路
考虑以下 DataFrame :
df = pd.DataFrame({"A":[2,3], "B":[4,5]}, index=["a","b"])
df
   A  B
a  2  4
b  3  5当 orient="records" 时,我们可以通过传入 lines=True 使每个项目出现在新行中,如下所示:
my_json = df.to_json(orient="records", lines=True)
my_json
'{"A":2,"B":4}\n{"A":3,"B":5}'当我们打印出字符串 my_json 时,我们会看到 \n 生效:
print(my_json)
{"A":2,"B":4}
{"A":3,"B":5}指定缩进
我们可以通过传入 indent 参数来添加空格缩进,如下所示:
my_json = df.to_json(orient="records", indent=3)
print(my_json)
[
   {
      "A":2,
      "B":4
   },
   {
      "A":3,
      "B":5
   }
]这里,第二行有 3 个空格,第三行有 6 个空格,依此类推。
相关用法
- Python Pandas DataFrame to_csv方法用法及代码示例
- Python Pandas DataFrame to_period方法用法及代码示例
- Python Pandas DataFrame to_timestamp方法用法及代码示例
- Python Pandas DataFrame to_numpy方法用法及代码示例
- Python Pandas DataFrame to_dict方法用法及代码示例
- Python PySpark DataFrame toDF方法用法及代码示例
- Python PySpark DataFrame toJSON方法用法及代码示例
- Python PySpark DataFrame toPandas方法用法及代码示例
- Python Pandas DataFrame tz_convert方法用法及代码示例
- Python Pandas DataFrame tail方法用法及代码示例
- Python Pandas DataFrame transform方法用法及代码示例
- Python Pandas DataFrame truncate方法用法及代码示例
- Python Pandas DataFrame tz_localize方法用法及代码示例
- Python Pandas DataFrame truediv方法用法及代码示例
- Python Pandas DataFrame transpose方法用法及代码示例
- Python Pandas DataFrame tshift方法用法及代码示例
- Python Pandas DataFrame take方法用法及代码示例
- Python PySpark DataFrame tail方法用法及代码示例
- Python PySpark DataFrame transform方法用法及代码示例
- Python PySpark DataFrame take方法用法及代码示例
- Python Pandas DataFrame empty属性用法及代码示例
- Python Pandas DataFrame pop方法用法及代码示例
- Python Pandas DataFrame nsmallest方法用法及代码示例
- Python Pandas DataFrame sample方法用法及代码示例
- Python Pandas DataFrame items方法用法及代码示例
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Pandas DataFrame | to_json method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
