首页 > 编程笔记 > Python笔记 阅读:2

Pandas JSON文件的处理(附带实例)

JSON(JavaScript Object Notation,JavaScript 对象表示法)是存储和交换文本信息的语法,类似 XML。

JSON 比 XML 更小、更快,更易解析。Pandas 可以很方便地处理 JSON 数据。

【实例】在 Pandas 中读取 JSON 文件并显示。
import pandas as pd
df = pd.read_json('sites.json')
print(df.to_string())

to_string() 用于返回 DataFrame 类型的数据,也可以直接处理 JSON 字符串,例如:
import pandas as pd
data = [
    {
        "id": "A001",
        "name": "C语言中文网",
        "url": "c.biancheng.net",
        "likes": 61
    },
    {
        "id": "A002",
        "name": "Google",
        "url": "www.google.com",
        "likes": 124
    },
    {
        "id": "A003",
        "name": "淘宝",
        "url": "www.taobao.com",
        "likes": 45
    }
]
df = pd.DataFrame(data)
print(df)
运行程序,输出如下:
   id   likes      name              url
0   01     61  C语言中文网      c.biancheng.net
1   02    124    Google         www.google.com
2   03     45     淘宝           www.taobao.com

JSON 对象与 Python 字典具有相同的格式,所以可以直接将 Python 字典转换为 DataFrame 数据。

【实例】将 JSON 对象的 Python 字典转换为 DataFrame 数据。
import pandas as pd
# 字典格式的 JSON
s = {
    "col1":{"row1":1,"row2":2,"row3":3},
    "col2":{"row1":"x","row2":"y","row3":"z"}
}
# 读取 JSON 转为 DataFrame
df = pd.DataFrame(s)
print(df)
运行程序,输出如下:
     col1 col2
row1    1    x
row2    2    y
row3    3    z

假设有一组内嵌的 JSON 数据文件 nested_list.json,使用以下代码格式化完整内容:
import pandas as pd
df = pd.read_json('nested_list.json')
print(df)
运行程序,输出如下:
school_name       class \
          0  ABC primary school  Year 1
          1  ABC primary school  Year 1
          2  ABC primary school  Year 1
                      students
0  {'id': '01', 'name': 'Tom', 'math': 50, 'physic...
1  {'id': '02', 'name': 'James', 'math': 69, 'physic...
2  {'id': '03', 'name': 'Jenny', 'math': 89, 'physic...

相关文章