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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
