Python Pandas - 读取和写入 JSON 文件
JSON (JavaScript Object Notation) 是一种轻量级、可读性强的数据交换格式,广泛用于数据存储和传输。它常用于服务器与 Web 应用程序之间传输数据。Python 的 Pandas 库提供了强大的功能,通过 read_json() 和 to_json() 方法高效地读取和写入 JSON 文件。
JSON 文件以结构化格式存储数据,看起来类似于 Python 中的 dictionary 或 list。JSON 文件的扩展名为 .json。下面可以看到 JSON 文件中数据的样子 −
[
{
"Name": "Braund",
"Gender": "Male",
"Age": 30
},
{
"Name": "Cumings",
"Gender": "Female",
"Age": 25
},
{
"Name": "Heikkinen",
"Gender": "female",
"Age": 35
}
]
在本教程中,我们将学习使用 Pandas 处理 JSON 文件的基础知识,包括读取和写入 JSON 文件,以及一些常见配置。
使用 Pandas 读取 JSON 文件
pandas.read_json() 函数用于将 JSON 数据读取到 Pandas DataFrame 中。该函数可以接受文件路径、URL 或 JSON 字符串作为输入。
示例
以下示例演示了如何使用 pandas.read_json() 函数读取 JSON 数据。这里我们使用 StringIO 将 JSON 字符串加载到文件对象中。
import pandas as pd
from io import StringIO
# 创建表示 JSON 数据的字符串
data = """[
{"Name": "Braund", "Gender": "Male", "Age": 30},
{"Name": "Cumings", "Gender": "Female", "Age": 25},
{"Name": "Heikkinen", "Gender": "Female", "Age": 35}
]"""
# 使用 StringIO 将 JSON 格式的字符串数据转换为文件对象
obj = StringIO(data)
# 将 JSON 读取到 Pandas DataFrame
df = pd.read_json(obj)
print(df)
以上代码的输出如下 −
| Name | Gender | Age | |
|---|---|---|---|
| 0 | Braund | Male | 30 |
| 1 | Cumings | Female | 25 |
| 2 | Heikkinen | Female | 35 |
使用 Pandas 写入 JSON 文件
Pandas 提供了 to_json() 函数,可以使用来自 Pandas DataFrame 或 Series 对象的数据导出或写入 JSON 文件。该函数用于将 Pandas 数据结构对象转换为 JSON 字符串,并提供多种配置选项来定制 JSON 输出。
示例:写入 JSON 文件的基本示例
以下示例演示了如何将 Pandas DataFrame 写入 JSON 文件。
import pandas as pd
# 从上面的字典创建 DataFrame
df = pd.DataFrame({"Name":["Braund", "Cumings", "Heikkinen"],
"Gender": ["Male", "Female", "Female"],
"Age": [30, 25, 25]})
print("原始 DataFrame:\n", df)
# 将 DataFrame 写入 JSON 文件
df.to_json("output_written_json_file.json", orient='records', lines=True)
print("输出 JSON 文件已成功写入。")
以下是上述代码的输出 −
Original DataFrame:
| Name | Gender | Age | |
|---|---|---|---|
| 0 | Braund | Male | 30 |
| 1 | Cumings | Female | 25 |
| 2 | Heikkinen | Female | 35 |
执行上述代码后,你可以在工作目录中找到名为 output_written_json_file.json 的创建的 JSON 文件。
示例:使用 split 方向写入 JSON 文件
以下示例使用 split 方向将简单的 DataFrame 对象写入 JSON。
import pandas as pd
from json import loads, dumps
# 创建 DataFrame
df = pd.DataFrame(
[["x", "y"], ["z", "w"]],
index=["row_1", "row_2"],
columns=["col_1", "col_2"],
)
# 使用 'split' 方向将 DataFrame 转换为 JSON
result = df.to_json(orient="split")
parsed = loads(result)
# 显示 JSON 输出
print("JSON 输出 (split 方向):")
print(dumps(parsed, indent=4))
以下是上述代码的输出 −
JSON Output (split orientation):
{
"columns": [
"col_1",
"col_2"
],
"index": [
"row_1",
"row_2"
],
"data": [
[
"x",
"y"
],
[
"z",
"w"
]
]
}