55_Pandas.DataFrame 轉(zhuǎn)換為 JSON 字符串/文件并保存 (to_json)
使用pandas.DataFrame的方法to_json(),可以將pandas.DataFrame轉(zhuǎn)為JSON格式字符串(str類型)或者輸出(保存)為JSON格式文件。
在此,對以下內(nèi)容進行說明。有關(guān)其他參數(shù),請參閱上面的官方文檔。
- pandas.DataFrame.to_json() 的基本用法
- 轉(zhuǎn)換為JSON格式字符串
- 輸出(保存)為JSON格式文件
- 文件壓縮:參數(shù)壓縮
- 指定格式:參數(shù)
orient
split
-
records
JSON Lines(.jsonl)
index
-
columns
(默認值) values
table
如果要將 pandas.DataFrame 轉(zhuǎn)換為字典(dict 類型),請使用 to_dict() 方法。
- 54_Pandas將DataFrame、Series轉(zhuǎn)換為字典 (to_dict)
另外,用pandas讀寫(輸入/輸出)CSV文件和Excel文件見以下文章。
- 03_Pandas讀取csv/tsv文件(read_csv,read_table)
- 34_Pandas對CSV文件內(nèi)容的導(dǎo)出和添加(to_csv)
- 50_Pandas讀取 Excel 文件 (xlsx, xls)
- 51_Pandas (to_excel) 編寫 Excel 文件 (xlsx, xls)
這里以創(chuàng)建如下 pandas.DataFrame 為例。
import pandas as pd
import pprint
import json
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['a', 'x', '啊']},
index=['row1', 'row2', 'row3'])
print(df)
# col1 col2
# row1 1 a
# row2 2 x
# row3 3 啊
pandas.DataFrame.to_json() 的基本用法
轉(zhuǎn)換為JSON格式字符串
當你從 pandas.DataFrame 調(diào)用 to_json() 方法時,默認情況下它被轉(zhuǎn)換為 JSON 格式字符串(str 類型),如下所示。
print(df.to_json())
# {"col1":{"row1":1,"row2":2,"row3":3},"col2":{"row1":"a","row2":"x","row3":"\u554a"}}
print(type(df.to_json()))
# <class 'str'>
非 ascii 字符(例如雙字節(jié)字符)是 Unicode 轉(zhuǎn)義的。如果參數(shù) force_ascii=False,則不會進行 Unicode 轉(zhuǎn)義。
輸出(保存)為JSON格式文件
如果您將路徑指定為第一個參數(shù),它將被保存為一個文件。未指定路徑時輸出的字符串按原樣寫入文件。
path = 'data/sample_from_pandas_columns.json'
df.to_json(path)
with open(path) as f:
s = f.read()
print(s)
print(type(s))
# {"col1":{"row1":1,"row2":2,"row3":3},"col2":{"row1":"a","row2":"x","row3":"\u554a"}}
# <class 'str'>
使用open()讀取時,參數(shù)encoding='unicode-escape’會將Unicode轉(zhuǎn)義序列\uXXXX
轉(zhuǎn)換為對應(yīng)的字符。
with open(path, encoding='unicode-escape') as f:
s = f.read()
print(s)
print(type(s))
# {"col1":{"row1":1,"row2":2,"row3":3},"col2":{"row1":"a","row2":"x","row3":"啊"}}
# <class 'str'>
使用標準庫 json 模塊的 json.load() 函數(shù)作為字典加載。在這種情況下,默認情況下 Unicode 轉(zhuǎn)義序列 \uXXXX
被轉(zhuǎn)換為相應(yīng)的字符。
with open(path) as f:
d = json.load(f)
print(d)
print(type(d))
# {'col1': {'row1': 1, 'row2': 2, 'row3': 3}, 'col2': {'row1': 'a', 'row2': 'x', 'row3': '啊'}}
# <class 'dict'>
文件壓縮:參數(shù)壓縮
通過指定從 pandas 版本 0.21.0 添加的參數(shù)壓縮,可以在輸出文件時壓縮文件。
指定“gzip”、“bz2”、“xz”之一。
df.to_json('data/sample_from_pandas_columns.gz', compression='gzip')
指定格式:參數(shù)orient
參數(shù)orient可以指定如何將pandas.DataFrame行標簽索引、列標簽列和值輸出為JSON。
在這里,還顯示了使用 json.loads() 將輸出字符串轉(zhuǎn)換為字典并使用 pprint() 顯示的結(jié)果。
split
{index -> [index], columns -> [columns], data -> [values]}
print(df.to_json(orient='split'))
# {"columns":["col1","col2"],"index":["row1","row2","row3"],"data":[[1,"a"],[2,"x"],[3,"\u554a"]]}
pprint.pprint(json.loads(df.to_json(orient='split')))
# {'columns': ['col1', 'col2'],
# 'data': [[1, 'a'], [2, 'x'], [3, '啊']],
# 'index': ['row1', 'row2', 'row3']}
records
[{column -> value}, ... , {column -> value}]
print(df.to_json(orient='records'))
# [{"col1":1,"col2":"a"},{"col1":2,"col2":"x"},{"col1":3,"col2":"\u554a"}]
pprint.pprint(json.loads(df.to_json(orient='records')), width=40)
# [{'col1': 1, 'col2': 'a'},
# {'col1': 2, 'col2': 'x'},
# {'col1': 3, 'col2': '啊'}]
JSON Lines(.jsonl)
如果參數(shù) orient='records,并且參數(shù) lines=True,它將是一個字符串,每個 {column: value} 都有一個換行符。
print(df.to_json(orient='records', lines=True))
# {"col1":1,"col2":"a"}
# {"col1":2,"col2":"x"}
# {"col1":3,"col2":"\u554a"}
index
{index -> {column -> value}}
print(df.to_json(orient='index'))
# {"row1":{"col1":1,"col2":"a"},"row2":{"col1":2,"col2":"x"},"row3":{"col1":3,"col2":"\u554a"}}
pprint.pprint(json.loads(df.to_json(orient='index')))
# {'row1': {'col1': 1, 'col2': 'a'},
# 'row2': {'col1': 2, 'col2': 'x'},
# 'row3': {'col1': 3, 'col2': '啊'}}
columns(默認值)
{column -> {index -> value}}
如果省略了 orient 參數(shù)(默認),則為這種格式。文章來源:http://www.zghlxwxcb.cn/news/detail-612186.html
print(df.to_json(orient='columns'))
# {"col1":{"row1":1,"row2":2,"row3":3},"col2":{"row1":"a","row2":"x","row3":"\u554a"}}
pprint.pprint(json.loads(df.to_json(orient='columns')))
# {'col1': {'row1': 1, 'row2': 2, 'row3': 3},
# 'col2': {'row1': 'a', 'row2': 'x', 'row3': '啊'}}
values
print(df.to_json(orient='values'))
# [[1,"a"],[2,"x"],[3,"\u554a"]]
pprint.pprint(json.loads(df.to_json(orient='values')))
# [[1, 'a'], [2, 'x'], [3, '啊']]
table
一種包含數(shù)據(jù)結(jié)構(gòu)方案信息的格式。文章來源地址http://www.zghlxwxcb.cn/news/detail-612186.html
print(df.to_json(orient='table'))
# {"schema": {"fields":[{"name":"index","type":"string"},{"name":"col1","type":"integer"},{"name":"col2","type":"string"}],"primaryKey":["index"],"pandas_version":"0.20.0"}, "data": [{"index":"row1","col1":1,"col2":"a"},{"index":"row2","col1":2,"col2":"x"},{"index":"row3","col1":3,"col2":"\u554a"}]}
pprint.pprint(json.loads(df.to_json(orient='table')))
# {'data': [{'col1': 1, 'col2': 'a', 'index': 'row1'},
# {'col1': 2, 'col2': 'x', 'index': 'row2'},
# {'col1': 3, 'col2': '啊', 'index': 'row3'}],
# 'schema': {'fields': [{'name': 'index', 'type': 'string'},
# {'name': 'col1', 'type': 'integer'},
# {'name': 'col2', 'type': 'string'}],
# 'pandas_version': '0.20.0',
# 'primaryKey': ['index']}}
到了這里,關(guān)于55_Pandas.DataFrame 轉(zhuǎn)換為 JSON 字符串/文件并保存 (to_json)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!