如何将 Pandas DataFrame 放入 JSON 文件中并再次读取?

pythonserver side programmingprogramming更新于 2025/10/27 19:24:17

要将 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 中读取数据。


相关文章


有用资源