Pandas DataFrames 是數據的表格表示,其中列代表單個數據條目中的各種數據點,每一行都是唯一的數據條目。而 JSON 是用 JavaScript 對象表示法編寫的文本。
將 Pandas DataFrame 轉換為 JSON
要將 Pandas DataFrames 轉換為 JSON 格式,我們使用DataFrame.to_json()
Python 中Pandas庫中的函數。to_json 函數中有多個自定義項可用於實現所需的 JSON 格式。看一下函數接受的參數,再探討定制
參數:
范圍 | 價值 | 用 |
---|---|---|
path_or_buf | 字符串或文件名,可選 | 文件路徑或對象。如果未指定,則結果作為字符串返回。 |
東方 | 'split', 'records', 'index', 'columns', 'values', 'table', default='index' | 指示預期的 JSON 字符串格式。 |
日期格式 | 無,“紀元”,“iso”,默認 =“紀元” | 日期轉換類型。'epoch' = 紀元毫秒,'iso' = ISO8601。默認值取決於方向。對於 orient='table',默認值為 'iso'。對於所有其他方向,默認值為 'epoch'。 |
雙精度 | 整數值,默認值=10 | 編碼浮點值時使用的小數位數。 |
force_ascii | 布爾值,默認值 = True | 強制編碼字符串為 ASCII。 |
日期_單位 | 's', 'ms', 'us', 'ns', default='ms' | 要編碼到的時間單位控制時間戳和 ISO8601 精度。這些值分別代表秒、毫秒、微秒和納秒。 |
默認處理程序 | 可調用函數 | 如果對象無法以其他方式轉換為適用於 JSON 的格式,則要調用的處理程序。應該接收一個參數,它是要轉換的對象並返回一個可序列化的對象。 |
線 | 布爾值,默認值 = False | 如果 'orient' 是 'records' 寫出行分隔的 json 格式。如果 'orient' 不正確,則會拋出 ValueError,因為其他人不是這樣的。 |
壓縮 | 'infer', 'gzip', 'bz2', 'zip', 'xz', None, default='infer' | 表示在輸出文件中使用的壓縮的字符串,僅在第一個參數是文件名時使用。默認情況下,壓縮是從文件名推斷的。 |
指數 | 布爾值,默認值 = True | 是否在 JSON 字符串中包含索引值。僅當 orient 為 'split' 或 'table' 時才支持不包括索引 (index=False)。 |
縮進 | 整數值 | 用於縮進每條記錄的空格長度。無需提及可選參數。 |
我們現在看幾個例子來理解函數DataFrame.to_json的用法。
示例 1:基本用法
import
numpy as np
import
pandas as pd
data
=
np.array([[
'1'
,
'2'
], [
'3'
,
'4'
]])
dataFrame
=
pd.DataFrame(data, columns
=
[
'col1'
,
'col2'
])
json
=
dataFrame.to_json()
print
(json)
|
輸出 :
{"col1":{"0":"1", "1":"3"}, "col2":{"0":"2", "1":"4"}}
示例 2:探索 DataFrame.to_json 函數的 'orient' 屬性
import numpy as np import pandas as pd data = np.array([['1', '2'], ['3', '4']]) dataFrame = pd.DataFrame(data, columns = ['col1', 'col2']) json = dataFrame.to_json() print(json) json_split = dataFrame.to_json(orient ='split') print("json_split = ", json_split, "\n") json_records = dataFrame.to_json(orient ='records') print("json_records = ", json_records, "\n") json_index = dataFrame.to_json(orient ='index') print("json_index = ", json_index, "\n") json_columns = dataFrame.to_json(orient ='columns') print("json_columns = ", json_columns, "\n") json_values = dataFrame.to_json(orient ='values') print("json_values = ", json_values, "\n") json_table = dataFrame.to_json(orient ='table') print("json_table = ", json_table, "\n")
|
輸出 :
json_split = {“columns”:[“col1”, “col2”], “index”:[0, 1], “data”:[[“1”, “2”], [“3”, “4”]]} json_records = [{“col1″:”1”, “col2″:”2”}, {“col1″:”3”, “col2″:”4”}] json_index = {“0”:{“col1″:”1”, “col2″:”2”}, “1”:{“col1″:”3”, “col2″:”4”}} json_columns = {“col1”:{“0″:”1”, “1”:”3″}, “col2”:{“0″:”2”, “1”:”4″}} json_values = [[“1”, “2”], [“3”, “4”]] json_table = {“schema”:{“fields”:[{“name”:”index”, “type”:”integer”}, {“name”:”col1″, “type”:”string”}, {“name”:”col2″, “type”:”string”}], “primaryKey”:[“index”], “pandas_version”:”0.20.0″}, “data”:[{“index”:0, “col1″:”1”, “col2″:”2”}, {“index”:1, “col1″:”3”, “col2″:”4”}]}
JSON 字符串的格式: - 'split' : dict like {'index' -> [index], 'columns' -> [columns], '數據' -> [值]} - 'records' : list like [{column -> value}, ... , {column -> value}] - 'index' : dict like {index -> {column -> value}} - 'columns' : dict like {column -> {index -> value}} - 'values' : 只是值數組 - 'table' : dict like {'schema': {schema}, 'data': {data}}
原始文檔介紹
""" 將對象轉換為 JSON 字符串。 注意 NaN 和 None 將被轉換為 null 和 datetime 對象 將轉換為 UNIX 時間戳。 參數 ---------- path_or_buf : str 或文件句柄,可選 文件路徑或對象。如果未指定,則返回結果為 一個字符串。 東方:str 指示預期的 JSON 字符串格式。 * 系列: - 默認為“索引” - 允許的值為:{'split','records','index','table'}。 * 數據框: - 默認為“列” - 允許的值為:{'split'、'records'、'index'、'columns'、 '值','表'}。 * JSON 字符串的格式: - 'split' : dict like {'index' -> [index], 'columns' -> [columns], '數據' -> [值]} - 'records' : list like [{column -> value}, ... , {column -> value}] - 'index' : dict like {index -> {column -> value}} - 'columns' : dict like {column -> {index -> value}} - 'values' : 只是值數組 - 'table' : dict like {'schema': {schema}, 'data': {data}} 描述數據,其中數據組件就像“orient='records'”。 .. 版本已更改:: 0.20.0 日期格式:{無,'紀元','iso'} 日期轉換類型。 'epoch' = 紀元毫秒, 'iso' = ISO8601。默認值取決於`orient`。為了 ``orient='table'``,默認為'iso'。對於所有其他方向, 默認值為“紀元”。 double_precision :int,默認為 10 編碼時使用的小數位數 浮點值。 force_ascii : bool,默認為 True 強制編碼字符串為 ASCII。 date_unit :str,默認'ms'(毫秒) 編碼到的時間單位,控制時間戳和 ISO8601 精確。 's'、'ms'、'us'、'ns' 之一表示秒、毫秒、 分別為微秒和納秒。 default_handler :可調用,默認無 如果對象不能以其他方式轉換為 JSON 的合適格式。應該接收一個參數是 要轉換並返回可序列化對象的對象。 行:布爾值,默認為假 如果 'orient' 是 'records' 寫出行分隔的 json 格式。將要 如果“東方”不正確,則拋出 ValueError,因為其他人未列出 喜歡。 壓縮:{'推斷'、'gzip'、'bz2'、'zip'、'xz'、無} 表示在輸出文件中使用的壓縮的字符串, 僅在第一個參數是文件名時使用。默認情況下, 從文件名推斷壓縮。 .. 版本添加:: 0.21.0 .. 版本已更改:: 0.24.0 添加了“推斷”選項並設置為默認值 索引:布爾值,默認為真 是否在 JSON 字符串中包含索引值。不是 僅在以下情況下才支持包含索引 (``index=False``) orient 是 'split' 或 'table'。 .. 版本已添加:: 0.23.0 縮進:整數,可選 用於縮進每條記錄的空格長度。 .. 版本已添加:: 1.0.0 退貨 ------- 無或 str 如果 path_or_buf 為 None,則返回生成的 json 格式作為 細繩。否則返回無。 也可以看看 -------- 讀取_json 筆記 ----- ``indent=0`` 的行為與 stdlib 不同,它不 縮進輸出但確實插入換行符。目前,“縮進=0” 和默認的“縮進=無”在熊貓中是等價的,盡管這 在未來的版本中可能會改變。 例子 -------- >>> df = pd.DataFrame([['a', 'b'], ['c', 'd']], ... index=['第 1 行','第 2 行'], ... columns=['col 1', 'col 2']) >>> df.to_json(orient='split') '{"columns":["col 1","col 2"], “索引”:[“第 1 行”,“第 2 行”], "數據":[["a","b"],["c","d"]]}' 使用“記錄”格式的 JSON 編碼/解碼數據幀。 請注意,此編碼不會保留索引標簽。 >>> df.to_json(orient='記錄') '[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]' 使用“索引”格式的 JSON 編碼/解碼數據幀: >>> df.to_json(orient='index') '{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d" }}' 使用“列”格式的 JSON 編碼/解碼數據幀: >>> df.to_json(orient='columns') '{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d" }}' 編碼/d