如何將 Pandas DataFrame 放入一個 JSON 檔案並再次讀取?
要將 Pandas DataFrame 放入一個 JSON 檔案並再次讀取,我們可以使用 to_json() 和 read_json() 方法。
步驟
- 建立一個二維、可變大小的、潛在異構的表格資料 df。
- 列印輸入 DataFrame,df。
- 使用 to_json() 方法將 DataFrame 轉儲到一個 JSON 檔案中。
- 使用 read_json() 方法讀取 JSON 檔案。
示例
import pandas as pd df = pd.DataFrame( { "x": [5, 2, 7, 0], "y": [4, 7, 5, 1], "z": [9, 3, 5, 1] } ) print "Input DataFrame is:\n", df print "JSON output for input DataFrame: ", df.to_json("test.json") print "Reading the created JSON file" print "Dataframe is: \n", pd.read_json("test.json")
輸出
Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 JSON output for input DataFrame: None Reading the created JSON file Dataframe is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1
當我們使用 df.to_json("test.json") 時,它會從 DataFrame 中給定的資料建立一個名為“test.json”的 JSON 檔案。
接下來,當我們使用 pd.read_json("test.json") 時,它會從 test.json 中讀取資料。
廣告