如何将 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 中读取数据。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP