Pandas JSON

简介: 10月更文挑战第27天

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

JSON 比 XML 更小、更快,更易解析,更多 JSON 内容可以参考 JSON 教程

Pandas 可以很方便的处理 JSON 数据,本文以 sites.json 为例,内容如下:

实例

[   {   "id": "A001",    "name": "菜鸟教程",    "url": "www.runoob.com",    "likes": 61   },    {   "id": "A002",    "name": "Google",    "url": "www.google.com",    "likes": 124   },    {   "id": "A003",    "name": "淘宝",    "url": "www.taobao.com",    "likes": 45   }]

实例

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": "菜鸟教程",

     "url": "www.runoob.com",

     "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    name             url  likes

0  A001    菜鸟教程  www.runoob.com     61

1  A002  Google  www.google.com    124

2  A003      淘宝  www.taobao.com     45

JSON 对象与 Python 字典具有相同的格式,所以我们可以直接将 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

从 URL 中读取 JSON 数据:

实例

import pandas as pd


URL = 'https://static.jyshare.com/download/sites.json'

df = pd.read_json(URL)

print(df)

以上实例输出结果为:

    id    name             url  likes

0  A001    菜鸟教程  www.runoob.com     61

1  A002  Google  www.google.com    124

2  A003      淘宝  www.taobao.com     45

内嵌的 JSON 数据

假设有一组内嵌的 JSON 数据文件 nested_list.json

nested_list.json 文件内容

{

   "school_name": "ABC primary school",

   "class": "Year 1",

   "students": [

   {

       "id": "A001",

       "name": "Tom",

       "math": 60,

       "physics": 66,

       "chemistry": 61

   },

   {

       "id": "A002",

       "name": "James",

       "math": 89,

       "physics": 76,

       "chemistry": 51

   },

   {

       "id": "A003",

       "name": "Jenny",

       "math": 79,

       "physics": 90,

       "chemistry": 78

   }]

}

使用以下代码格式化完整内容:

实例

import pandas as pd


df = pd.read_json('nested_list.json')


print(df)

以上实例输出结果为:

         school_name   class                                           students

0  ABC primary school  Year 1  {'id': 'A001', 'name': 'Tom', 'math': 60, 'phy...

1  ABC primary school  Year 1  {'id': 'A002', 'name': 'James', 'math': 89, 'p...

2  ABC primary school  Year 1  {'id': 'A003', 'name': 'Jenny', 'math': 79, 'p...

这时我们就需要使用到 json_normalize() 方法将内嵌的数据完整的解析出来:

实例

import pandas as pd

import json


# 使用 Python JSON 模块载入数据

with open('nested_list.json','r') as f:

   data = json.loads(f.read())


# 展平数据

df_nested_list = pd.json_normalize(data, record_path =['students'])

print(df_nested_list)

以上实例输出结果为:

    id   name  math  physics  chemistry

0  A001    Tom    60       66         61

1  A002  James    89       76         51

2  A003  Jenny    79       90         78

data = json.loads(f.read()) 使用 Python JSON 模块载入数据。

json_normalize() 使用了参数 record_path 并设置为 ['students'] 用于展开内嵌的 JSON 数据 students

显示结果还没有包含 school_name 和 class 元素,如果需要展示出来可以使用 meta 参数来显示这些元数据:

实例

import pandas as pd

import json


# 使用 Python JSON 模块载入数据

with open('nested_list.json','r') as f:

   data = json.loads(f.read())


# 展平数据

df_nested_list = pd.json_normalize(

   data,

   record_path =['students'],

   meta=['school_name', 'class']

)

print(df_nested_list)

以上实例输出结果为:

    id   name  math  physics  chemistry         school_name   class

0  A001    Tom    60       66         61  ABC primary school  Year 1

1  A002  James    89       76         51  ABC primary school  Year 1

2  A003  Jenny    79       90         78  ABC primary school  Year 1

接下来,让我们尝试读取更复杂的 JSON 数据,该数据嵌套了列表和字典,数据文件 nested_mix.json 如下:

nested_mix.json 文件内容

{

   "school_name": "local primary school",

   "class": "Year 1",

   "info": {

     "president": "John Kasich",

     "address": "ABC road, London, UK",

     "contacts": {

       "email": "admin@e.com",

       "tel": "123456789"

     }

   },

   "students": [

   {

       "id": "A001",

       "name": "Tom",

       "math": 60,

       "physics": 66,

       "chemistry": 61

   },

   {

       "id": "A002",

       "name": "James",

       "math": 89,

       "physics": 76,

       "chemistry": 51

   },

   {

       "id": "A003",

       "name": "Jenny",

       "math": 79,

       "physics": 90,

       "chemistry": 78

   }]

}

nested_mix.json 文件转换为 DataFrame:

实例

import pandas as pd

import json


# 使用 Python JSON 模块载入数据

with open('nested_mix.json','r') as f:

   data = json.loads(f.read())

 

df = pd.json_normalize(

   data,

   record_path =['students'],

   meta=[

       'class',

       ['info', 'president'],

       ['info', 'contacts', 'tel']

   ]

)


print(df)

以上实例输出结果为:

    id   name  math  physics  chemistry   class info.president info.contacts.tel

0  A001    Tom    60       66         61  Year 1    John Kasich         123456789

1  A002  James    89       76         51  Year 1    John Kasich         123456789

2  A003  Jenny    79       90         78  Year 1    John Kasich         123456789

读取内嵌数据中的一组数据

以下是实例文件 nested_deep.json,我们只读取内嵌中的 math 字段:

nested_deep.json 文件内容

{

   "school_name": "local primary school",

   "class": "Year 1",

   "students": [

   {

       "id": "A001",

       "name": "Tom",

       "grade": {

           "math": 60,

           "physics": 66,

           "chemistry": 61

       }

 

   },

   {

       "id": "A002",

       "name": "James",

       "grade": {

           "math": 89,

           "physics": 76,

           "chemistry": 51

       }

     

   },

   {

       "id": "A003",

       "name": "Jenny",

       "grade": {

           "math": 79,

           "physics": 90,

           "chemistry": 78

       }

   }]

}

这里我们需要使用到 glom 模块来处理数据套嵌,glom 模块允许我们使用 . 来访问内嵌对象的属性。

第一次使用我们需要安装 glom:

pip3 install glom

实例

import pandas as pd

from glom import glom


df = pd.read_json('nested_deep.json')


data = df['students'].apply(lambda row: glom(row, 'grade.math'))

print(data)

以上实例输出结果为:

0    60

1    89

2    79

Name: students, dtype: int64

目录
相关文章
|
6月前
|
存储 JSON 数据格式
Pandas 使用教程 CSV - CSV 转 JSON
Pandas 使用教程 CSV - CSV 转 JSON
54 0
|
6月前
|
JSON 数据格式 Python
Pandas 使用教程 JSON
Pandas 使用教程 JSON
59 0
|
9月前
|
存储 JSON 关系型数据库
Pandas载入txt、csv、Excel、JSON、数据库文件讲解及实战(超详细 附源码)
Pandas载入txt、csv、Excel、JSON、数据库文件讲解及实战(超详细 附源码)
175 0
|
JSON 关系型数据库 MySQL
pandas数据加载(csv、excel、json、mysql、webAPI)
数据的输入是数据分析的第一步,如果不能将数据快速方便的导入导出python,那么pandas不可能成为强大而高效的数据分析环境,本文重点介绍pandas的数据输入加载。
249 0
pandas数据加载(csv、excel、json、mysql、webAPI)
|
JSON 数据可视化 数据挖掘
python数据可视化开发(2):pandas读取Excel的数据格式处理(数据读取、指定列数据、DataFrame转json、数学运算、透视表运算输出)
python数据可视化开发(2):pandas读取Excel的数据格式处理(数据读取、指定列数据、DataFrame转json、数学运算、透视表运算输出)
412 0
|
JSON 数据挖掘 数据格式
Pandas处理JSON文件read_json()一文详解+代码展示
Pandas处理JSON文件read_json()一文详解+代码展示
1685 0
Pandas处理JSON文件read_json()一文详解+代码展示
|
存储 JSON 数据格式
Pandas处理JSON文件to_json()一文详解+实例代码
Pandas处理JSON文件to_json()一文详解+实例代码
1707 0
Pandas处理JSON文件to_json()一文详解+实例代码
|
30天前
|
JSON 缓存 API
解析电商商品详情API接口系列,json数据示例参考
电商商品详情API接口是电商平台的重要组成部分,提供了商品的详细信息,支持用户进行商品浏览和购买决策。通过合理的API设计和优化,可以提升系统性能和用户体验。希望本文的解析和示例能够为开发者提供参考,帮助构建高效、可靠的电商系统。
39 12
|
1月前
|
JSON 前端开发 搜索推荐
关于商品详情 API 接口 JSON 格式返回数据解析的示例
本文介绍商品详情API接口返回的JSON数据解析。最外层为`product`对象,包含商品基本信息(如id、name、price)、分类信息(category)、图片(images)、属性(attributes)、用户评价(reviews)、库存(stock)和卖家信息(seller)。每个字段详细描述了商品的不同方面,帮助开发者准确提取和展示数据。具体结构和字段含义需结合实际业务需求和API文档理解。
|
3月前
|
JSON API 数据安全/隐私保护
拍立淘按图搜索API接口返回数据的JSON格式示例
拍立淘按图搜索API接口允许用户通过上传图片来搜索相似的商品,该接口返回的通常是一个JSON格式的响应,其中包含了与上传图片相似的商品信息。以下是一个基于淘宝平台的拍立淘按图搜索API接口返回数据的JSON格式示例,同时提供对其关键字段的解释