Pandas JSON

Pandas 提供了 `read_json()` 和 `to_json()` 等方法来处理 JSON(JavaScript Object Notation)数据。

JSON 是一种纯文本文件,其格式类似于 JavaScript 对象。它由键值对组成,其中键是字符串,值可以是字符串、数字、布尔值、数组,甚至是其他 JSON 对象。

这是一个 JSON 示例。

[
  {
    "name": "John",
    "age": 30,
    "city": "New York"
  },
  {
    "name": "Emily",
    "age": 28,
    "city": "San Francisco"
  },
  {
    "name": "David",
    "age": 35,
    "city": "Chicago"
  }
]

我们将这个 JSON 文件命名为 `data.json`。


在 Pandas 中读取 JSON

要将 JSON 数据读取到 Pandas 的 DataFrame 中,您可以使用 `read_json()` 函数。

让我们读取之前创建的 `data.json` 文件。

import pandas as pd

df = pd.read_json('data.json')
print(df)

输出

    name  age           city
0   John   30       New York
1  Emily   28  San Francisco
2  David   35        Chicago

上面的代码读取 `data.json` 文件的内容,并创建一个名为 `df` 的 DataFrame,其中包含来自 JSON 文件的数据。

注意: 上面的代码要正常工作,`data.json` 文件必须位于当前目录中。如果它在其他目录中,您需要提供文件的完整路径。

例如,如果 `data.json` 文件位于 `json_files` 文件夹中,则应将路径 `'./json_files/data.json'` 指定为

df = pd.read_json('./json_files/data.json', header = 0)

read_json() 语法

Pandas 中 `read_json()` 的语法是

df = pd.read_json(filepath_or_buffer, orient=None, typ='frame', numpy=False, precise_float=False,encoding=None,lines=False)

这里,

  • filepath_or_buffer(可选):指定 JSON 文件或包含 JSON 数据的类文件对象的路径或 URL
  • orient(可选):指定 JSON 文件的方向
  • typ(可选):指示预期的输出类型
  • precise_float(可选):指定是否精确解析浮点数
  • encoding(可选):指定读取 JSON 文件时要使用的编码
  • lines(可选):控制数据读取过程的各个方面

这些是 `read_json()` 函数的一些常用参数。还有许多其他可选参数可以与 `read_json()` 一起使用。

要了解更多信息,请参阅官方文档中关于 `read_json()` 的内容:read_json()


示例:读取 JSON

假设我们有一个名为 `data.json` 的 CSV 文件,内容如下

[[1, "John", 25.12345],[2, "Jane", 30.98765432155],[3, "Alex", 28.56]]

在这里,JSON 包含同一行中的数组或数组。因此,我们将必需的参数传递给 `read_json()` 方法。

现在,让我们将此 JSON 文件加载到 DataFrame 中。

import pandas as pd

df = pd.read_json('data.json', orient = 'values', lines = False)
print(df)

输出

   0     1          2
0  1  John  25.123450
1  2  Jane  30.987654
2  3  Alex  28.560000

在此示例中,我们使用 `read_json()` 读取了一个包含数组的 JSON 文件。在读取文件时,我们指定了一些参数以将必要的数据加载到适当的格式。

这里,

  • orient = 'values':指定 JSON 文件包含数组的数组
  • lines = False:指示 JSON 文件不包含每行独立的一行

为了可视化 orient 和 lines 参数的效果,让我们看一个不同格式的 JSON。

{"id": 1, "name": "John", "value": 25.12345}
{"id": 2, "name": "Jane", "value": 30.98765432155}
{"id": 3, "name": "Alex", "value": 28.56}

请注意,上面的 JSON 格式不正确。我们仅使用它来演示指定参数的用法。

现在,让我们从 `data.json` 读取上面的 JSON。

import pandas as pd

df = pd.read_json('data.json', orient = 'records', lines = True)
print(df)

输出

   id  name      value
0   1  John  25.123450
1   2  Jane  30.987654
2   3  Alex  28.560000

这里,

  • orient = 'records':指定 JSON 文件包含键值对格式的数据
  • lines = True:指示 JSON 文件包含每行独立的一行

在 Pandas 中写入 JSON

要将 Pandas DataFrame 写入 JSON 文件,您可以使用 `to_json()` 函数。例如,

import pandas as pd

# create a dictionary
data = {'Name': ['John', 'Alice', 'Bob'],
        'Age': [25, 30, 35],
        'City': ['New York', 'London', 'Paris']}

# create a dataframe from the dictionary
df = pd.DataFrame(data)

# write dataframe to json file df.to_json('output.json')

输出

{"Name":{"0":"John","1":"Alice","2":"Bob"},"Age":{"0":25,"1":30,"2":35},"City":{"0":"New York","1":"London","2":"Paris"}}

上面的代码片段将 `df` DataFrame 写入 `output.json` 文件。


to_json() 语法

Pandas 中 `to_json()` 的语法是

df.to_json(
    path_or_buf,
    orient= 'columns',
    lines=False,
    compression='infer', 
    index=True
)

这里,

  • path_or_buf(可选):指定写入 JSON 字符串的文件路径或缓冲区
  • orient(可选):指定 JSON 字符串的格式
  • lines(可选):指定生成的 JSON 字符串是否应采用行分隔格式
  • compression(可选):指定文件输出的压缩算法
  • index(可选):指定是否在 JSON 字符串中包含 DataFrame 的索引

这些是 `to_json()` 函数的一些常用参数。还有许多其他可选参数可以与 `to_json()` 一起使用。

要了解更多信息,请参阅官方文档中关于 `to_json()` 的内容:to_json()


示例:写入 JSON

import pandas as pd

# create a dictionary
data = {'Name': ['John', 'Alice', 'Bob'],
             'Age': [25, 30, 35],
             'City': ['New York', 'London', 'Paris']}

# create a dataframe from the dictionary
df = pd.DataFrame(data)

# write dataframe to json file df.to_json('output.json', orient = 'records', indent = 4)

输出

[
    {
        "Name":"John",
        "Age":25,
        "City":"New York"
    },
    {
        "Name":"Alice",
        "Age":30,
        "City":"London"
    },
    {
        "Name":"Bob",
        "Age":35,
        "City":"Paris"
    }
]

在此示例中,我们将 DataFrame `df` 导出到 `output.json` 文件。

这里,

  • orient = 'records':将 DataFrame 中的每一行表示为一个 JSON 对象
  • indent = 4:将缩进使用的空格数设置为 **4**

注意: 上面的代码将在当前目录中创建一个名为 `output.json` 的新文件(除非在文件路径中指定了其他目录)。

如果 `output.json` 文件已存在于当前目录中,则运行此代码将用 DataFrame 的新内容覆盖现有文件。

要了解更多信息,请参阅官方文档中关于 `read_json()` 和 `to_json()` 的内容:read_json()to_json()


常见问题

如何在 Pandas 中读取 JSON 字符串?

我们可以使用 `read_json()` 将 JSON 字符串读取到 DataFrame 中。例如,

import pandas as pd

# create a JSON string
json_string = '''
[
  {
    "name": "John",
    "age": 30,
    "city": "New York"
  },
  {
    "name": "Emily",
    "age": 28,
    "city": "San Francisco"
  },
  {
    "name": "David",
    "age": 35,
    "city": "Chicago"
  }
]
'''

# read json data from string into a dataframe df = pd.read_json(json_string)
# display the dataframe print(df)

输出

     name  age           city
 0   John   30       New York
 1  Emily   28  San Francisco
 2  David   35        Chicago

在这里,我们将 JSON 字符串作为参数传递给 `read_json()` 以将字符串转换为 DataFrame。

如何将 DataFrame 写入 JSON 字符串?

我们可以使用 `to_json()` 将 Pandas DataFrame 写入 JSON 字符串。例如,

import pandas as pd

# create a dictionary
data = {'Name': ['John', 'Alice', 'Bob'],
             'Age': [25, 30, 35],
             'City': ['New York', 'London', 'Paris']}

# create a dataframe from the dictionary
df = pd.DataFrame(data)

# write dataframe to json string json_string = df.to_json(orient='records', indent = 4)
# display the string print(json_string)

输出

[
    {
        "Name":"John",
        "Age":25,
        "City":"New York"
    },
    {
        "Name":"Alice",
        "Age":30,
        "City":"London"
    },
    {
        "Name":"Bob",
        "Age":35,
        "City":"Paris"
    }
]

在上面的示例中,我们使用 `to_json()` 将 DataFrame 字典转换为 JSON 字符串。

如何将嵌套的 JSON 转换为 DataFrame?

在 Pandas 中,可以使用 `json_normalize()` 将嵌套的 JSON 展平为 DataFrame。

`json_normalize()` 函数接受 Python 字典 或字典列表形式的 JSON 对象,并返回一个 DataFrame。例如,

import pandas as pd

# create a nested json object
data = {
    "name": "John",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "New York",
        "state": "NY"
    }
}

# convert json to dataframe df = pd.json_normalize(data)
# display the dataframe print(df)

输出

   name  age address.street address.city address.state
0  John   30    123 Main St     New York            NY

另请参阅

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战