JSON 入門

使用 pandas 的精實資料導入

Amany Mahfouz

Instructor

Javascript Object Notation(JSON)

  • 常見的網路資料格式
  • 非表格結構
    • 各筆紀錄不一定有相同屬性
  • 資料以物件集合組成
  • 物件為屬性-值配對的集合
  • 巢狀 JSON:物件中還有物件
使用 pandas 的精實資料導入

讀取 JSON 資料

  • read_json()
    • 接受 JSON 檔案路徑字串,或 JSON 內容字串
    • dtype 參數指定資料型別
    • orient 參數標示較少見的 JSON 版型
      • 可能值見 pandas 文件
使用 pandas 的精實資料導入

資料取向(Orientation)

  • JSON 不是表格資料
    • pandas 會推測如何排成表格
  • pandas 可自動處理常見取向
使用 pandas 的精實資料導入

Record 取向

  • 最常見的 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 的精實資料導入

Column 取向

  • 比 record 取向更省空間
    {
      "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 的精實資料導入

指定取向

  • Split 取向資料-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 的精實資料導入

一起來練習吧!

使用 pandas 的精實資料導入

Preparing Video For Download...