JSON 简介

使用 pandas 高效导入数据

Amany Mahfouz

Instructor

JavaScript 对象表示法(JSON)

  • 常见的 Web 数据格式
  • 非表格型
    • 记录不必具有相同属性集
  • 数据组织为对象集合
  • 对象是属性-值对的集合
  • 嵌套 JSON:对象内含对象
使用 pandas 高效导入数据

读取 JSON 数据

  • read_json()
    • 接受 JSON 的路径字符串,或 JSON 字符串本身
    • dtype 关键字参数指定数据类型
    • orient 标注非常见 JSON 布局
      • 取值见 pandas 文档
使用 pandas 高效导入数据

数据取向

  • JSON 不是表格数据
    • pandas 会推断表格化方式
  • pandas 可自动处理常见取向
使用 pandas 高效导入数据

记录取向

  • 最常见的 JSON 布局
    [
      {
          "age_adjusted_death_rate": "7.6",
          "death_rate": "6.2",
          "deaths": "32",
          "leading_cause": "Accidents Except Drug Posioning (V01-X39, X43, X45-X59, Y85-Y86)",
          "race_ethnicity": "Asian and Pacific Islander",
          "sex": "F",
          "year": "2007"
      },
      {
          "age_adjusted_death_rate": "8.1",
          "death_rate": "8.3",
          "deaths": "87",
          ...
    
使用 pandas 高效导入数据

列取向

  • 比记录取向更省空间
    {
      "age_adjusted_death_rate": {
          "0": "7.6",
          "1": "8.1",
          "2": "7.1",
          "3": ".",
          "4": ".",
          "5": "7.3",
          "6": "13",
          "7": "20.6",
          "8": "17.4",
          "9": ".",
          "10": ".",
          "11": "19.8",
          ...
    
使用 pandas 高效导入数据

指定取向

  • 拆分取向数据 - nyc_death_causes.json
    {
      "columns": [
          "age_adjusted_death_rate",
          "death_rate",
          "deaths",
          "leading_cause",
          "race_ethnicity",
          "sex",
          "year"
      ],
      "index": [...],
      "data": [
          [
              "7.6",
    
使用 pandas 高效导入数据

指定取向

import pandas as pd

death_causes = pd.read_json("nyc_death_causes.json", orient="split")
print(death_causes.head())
  age_adjusted_death_rate death_rate deaths             leading_cause              race_ethnicity sex  year
0                     7.6        6.2     32  Accidents Except Drug...  Asian and Pacific Islander   F  2007
1                     8.1        8.3     87  Accidents Except Drug...          Black Non-Hispanic   F  2007
2                     7.1        6.1     71  Accidents Except Drug...                    Hispanic   F  2007
3                       .          .      .  Accidents Except Drug...          Not Stated/Unknown   F  2007
4                       .          .      .  Accidents Except Drug...       Other Race/ Ethnicity   F  2007

[5 rows x 7 columns]
使用 pandas 高效导入数据

Vamos praticar!

使用 pandas 高效导入数据

Preparing Video For Download...