: | : | :期货程序化 | :期货程序化研究 | :期货量化学习 | :期货量化 |
返回列表 发帖

【Pandas 教程系列】- Pandas JSON

【Pandas 教程系列】- Pandas JSON

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

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

Pandas 可以很方便的处理 JSON 数据,本文以 sites.json 【https://static.jyshare.com/download/sites.json】为例,内容如下:

实例
  1. [
  2.    {
  3.    "id": "A001",
  4.    "name": "菜鸟教程",
  5.    "url": "www.runoob.com",
  6.    "likes": 61
  7.    },
  8.    {
  9.    "id": "A002",
  10.    "name": "Google",
  11.    "url": "www.google.com",
  12.    "likes": 124
  13.    },
  14.    {
  15.    "id": "A003",
  16.    "name": "淘宝",
  17.    "url": "www.taobao.com",
  18.    "likes": 45
  19.    }
  20. ]
复制代码
实例
  1. import pandas as pd

  2. df = pd.read_json('sites.json')
  3.    
  4. print(df.to_string())
复制代码
to_string() 用于返回 DataFrame 类型的数据,我们也可以直接处理 JSON 字符串。

实例
  1. import pandas as pd

  2. data =[
  3.     {
  4.       "id": "A001",
  5.       "name": "菜鸟教程",
  6.       "url": "www.runoob.com",
  7.       "likes": 61
  8.     },
  9.     {
  10.       "id": "A002",
  11.       "name": "Google",
  12.       "url": "www.google.com",
  13.       "likes": 124
  14.     },
  15.     {
  16.       "id": "A003",
  17.       "name": "淘宝",
  18.       "url": "www.taobao.com",
  19.       "likes": 45
  20.     }
  21. ]
  22. df = pd.DataFrame(data)

  23. print(df)
复制代码
以上实例输出结果为:
  1.      id    name             url  likes
  2. 0  A001    菜鸟教程  www.runoob.com     61
  3. 1  A002  Google  www.google.com    124
  4. 2  A003      淘宝  www.taobao.com     45
复制代码
JSON 对象与 Python 字典具有相同的格式,所以我们可以直接将 Python 字典转化为 DataFrame 数据:

实例
  1. import pandas as pd


  2. # 字典格式的 JSON                                                                                             
  3. s = {
  4.     "col1":{"row1":1,"row2":2,"row3":3},
  5.     "col2":{"row1":"x","row2":"y","row3":"z"}
  6. }

  7. # 读取 JSON 转为 DataFrame                                                                                          
  8. df = pd.DataFrame(s)
  9. print(df)
复制代码
以上实例输出结果为:
  1.       col1 col2
  2. row1     1    x
  3. row2     2    y
  4. row3     3    z
复制代码
从 URL 中读取 JSON 数据:

实例
  1. import pandas as pd

  2. URL = 'https://static.jyshare.com/download/sites.json'
  3. df = pd.read_json(URL)
  4. print(df)
复制代码
以上实例输出结果为:
  1.      id    name             url  likes
  2. 0  A001    菜鸟教程  www.runoob.com     61
  3. 1  A002  Google  www.google.com    124
  4. 2  A003      淘宝  www.taobao.com     45
复制代码
内嵌的 JSON 数据
假设有一组内嵌的 JSON 数据文件 nested_list.json :

nested_list.json 文件内容
  1. {
  2.     "school_name": "ABC primary school",
  3.     "class": "Year 1",
  4.     "students": [
  5.     {
  6.         "id": "A001",
  7.         "name": "Tom",
  8.         "math": 60,
  9.         "physics": 66,
  10.         "chemistry": 61
  11.     },
  12.     {
  13.         "id": "A002",
  14.         "name": "James",
  15.         "math": 89,
  16.         "physics": 76,
  17.         "chemistry": 51
  18.     },
  19.     {
  20.         "id": "A003",
  21.         "name": "Jenny",
  22.         "math": 79,
  23.         "physics": 90,
  24.         "chemistry": 78
  25.     }]
  26. }
复制代码
使用以下代码格式化完整内容:

实例
  1. import pandas as pd

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

  3. print(df)
复制代码
以上实例输出结果为:
  1.           school_name   class                                           students
  2. 0  ABC primary school  Year 1  {'id': 'A001', 'name': 'Tom', 'math': 60, 'phy...
  3. 1  ABC primary school  Year 1  {'id': 'A002', 'name': 'James', 'math': 89, 'p...
  4. 2  ABC primary school  Year 1  {'id': 'A003', 'name': 'Jenny', 'math': 79, 'p...
复制代码
这时我们就需要使用到 json_normalize() 方法将内嵌的数据完整的解析出来:

实例
  1. import pandas as pd
  2. import json

  3. # 使用 Python JSON 模块载入数据
  4. with open('nested_list.json','r') as f:
  5.     data = json.loads(f.read())

  6. # 展平数据
  7. df_nested_list = pd.json_normalize(data, record_path =['students'])
  8. print(df_nested_list)
复制代码
以上实例输出结果为:
  1.      id   name  math  physics  chemistry
  2. 0  A001    Tom    60       66         61
  3. 1  A002  James    89       76         51
  4. 2  A003  Jenny    79       90         78
复制代码
data = json.loads(f.read()) 使用 Python JSON 模块载入数据。

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

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

实例
  1. import pandas as pd
  2. import json

  3. # 使用 Python JSON 模块载入数据
  4. with open('nested_list.json','r') as f:
  5.     data = json.loads(f.read())

  6. # 展平数据
  7. df_nested_list = pd.json_normalize(
  8.     data,
  9.     record_path =['students'],
  10.     meta=['school_name', 'class']
  11. )
  12. print(df_nested_list)
复制代码
以上实例输出结果为:
  1.      id   name  math  physics  chemistry         school_name   class
  2. 0  A001    Tom    60       66         61  ABC primary school  Year 1
  3. 1  A002  James    89       76         51  ABC primary school  Year 1
  4. 2  A003  Jenny    79       90         78  ABC primary school  Year 1
复制代码
接下来,让我们尝试读取更复杂的 JSON 数据,该数据嵌套了列表和字典,数据文件 nested_mix.json 如下:

nested_mix.json 文件内容
  1. {
  2.     "school_name": "local primary school",
  3.     "class": "Year 1",
  4.     "info": {
  5.       "president": "John Kasich",
  6.       "address": "ABC road, London, UK",
  7.       "contacts": {
  8.         "email": "admin@e.com",
  9.         "tel": "123456789"
  10.       }
  11.     },
  12.     "students": [
  13.     {
  14.         "id": "A001",
  15.         "name": "Tom",
  16.         "math": 60,
  17.         "physics": 66,
  18.         "chemistry": 61
  19.     },
  20.     {
  21.         "id": "A002",
  22.         "name": "James",
  23.         "math": 89,
  24.         "physics": 76,
  25.         "chemistry": 51
  26.     },
  27.     {
  28.         "id": "A003",
  29.         "name": "Jenny",
  30.         "math": 79,
  31.         "physics": 90,
  32.         "chemistry": 78
  33.     }]
  34. }
复制代码
nested_mix.json 文件转换为 DataFrame:

实例
  1. import pandas as pd
  2. import json

  3. # 使用 Python JSON 模块载入数据
  4. with open('nested_mix.json','r') as f:
  5.     data = json.loads(f.read())
  6.    
  7. df = pd.json_normalize(
  8.     data,
  9.     record_path =['students'],
  10.     meta=[
  11.         'class',
  12.         ['info', 'president'],
  13.         ['info', 'contacts', 'tel']
  14.     ]
  15. )

  16. print(df)
复制代码
以上实例输出结果为:
  1.      id   name  math  physics  chemistry   class info.president info.contacts.tel
  2. 0  A001    Tom    60       66         61  Year 1    John Kasich         123456789
  3. 1  A002  James    89       76         51  Year 1    John Kasich         123456789
  4. 2  A003  Jenny    79       90         78  Year 1    John Kasich         123456789
复制代码
读取内嵌数据中的一组数据

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

nested_deep.json 文件内容
  1. {
  2.     "school_name": "local primary school",
  3.     "class": "Year 1",
  4.     "students": [
  5.     {
  6.         "id": "A001",
  7.         "name": "Tom",
  8.         "grade": {
  9.             "math": 60,
  10.             "physics": 66,
  11.             "chemistry": 61
  12.         }

  13.     },
  14.     {
  15.         "id": "A002",
  16.         "name": "James",
  17.         "grade": {
  18.             "math": 89,
  19.             "physics": 76,
  20.             "chemistry": 51
  21.         }
  22.       
  23.     },
  24.     {
  25.         "id": "A003",
  26.         "name": "Jenny",
  27.         "grade": {
  28.             "math": 79,
  29.             "physics": 90,
  30.             "chemistry": 78
  31.         }
  32.     }]
  33. }
复制代码
这里我们需要使用到 glom 模块来处理数据套嵌,glom 模块允许我们使用 . 来访问内嵌对象的属性。

第一次使用我们需要安装 glom:
  1. pip3 install glom
复制代码
实例
  1. import pandas as pd
  2. from glom import glom

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

  4. data = df['students'].apply(lambda row: glom(row, 'grade.math'))
  5. print(data)
复制代码
以上实例输出结果为:
  1. 0    60
  2. 1    89
  3. 2    79
  4. Name: students, dtype: int64
复制代码

论坛官方微信、群(期货热点、量化探讨、开户与绑定实盘)
 
期货论坛 - 版权/免责声明   1.本站发布源码(包括函数、指标、策略等)均属开放源码,用意在于让使用者学习程序化语法撰写,使用者可以任意修改语法內容并调整参数。仅限用于个人学习使用,请勿转载、滥用,严禁私自连接实盘账户交易
  2.本站发布资讯(包括文章、视频、历史记录、教材、评论、资讯、交易方案等)均系转载自网络主流媒体,内容仅为作者当日个人观点,本网转载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。本网不对该类信息或数据做任何保证。不对您构成任何投资建议,不能依靠信息而取代自身独立判断,不对因使用本篇文章所诉信息或观点等导致的损失承担任何责任。
  3.本站发布资源(包括书籍、杂志、文档、软件等)均从互联网搜索而来,仅供个人免费交流学习,不可用作商业用途,本站不对显示的内容承担任何责任。请在下载后24小时内删除。如果喜欢,请购买正版,谢谢合作!
  4.龙听期货论坛原创文章属本网版权作品,转载须注明来源“龙听期货论坛”,违者本网将保留追究其相关法律责任的权力。本论坛除发布原创文章外,亦致力于优秀财经文章的交流分享,部分文章推送时若未能及时与原作者取得联系并涉及版权问题时,请及时联系删除。联系方式:http://www.qhlt.cn/thread-262-1-1.html
如何访问权限为100/255贴子:/thread-37840-1-1.html;注册后仍无法回复:/thread-23-1-1.html;微信/QQ群:/thread-262-1-1.html;网盘链接失效解决办法:/thread-93307-1-1.html

返回列表