要将 Pandas DataFrame 放入 JSON 文件并再次读取,我们可以使用to_json()和read_json()方法。
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧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 输出: ", 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 输出: 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读取数据。