Làm việc với JSON lồng nhau

Nạp dữ liệu gọn nhẹ với pandas

Amany Mahfouz

Instructor

JSON lồng nhau

  • JSON gồm các đối tượng với cặp thuộc tính-giá trị
  • JSON là lồng nhau khi giá trị cũng là một đối tượng
Nạp dữ liệu gọn nhẹ với pandas

Ví dụ phản hồi JSON từ tài liệu Yelp Business API

Nạp dữ liệu gọn nhẹ với pandas

Ví dụ phản hồi Yelp, nổi bật tọa độ và địa chỉ lồng nhau

Nạp dữ liệu gọn nhẹ với pandas

Ví dụ phản hồi Yelp, nổi bật dữ liệu category lồng nhau

Nạp dữ liệu gọn nhẹ với pandas

Ví dụ phản hồi Yelp, làm nổi bật bản ghi lồng dưới businesses

Nạp dữ liệu gọn nhẹ với pandas
# In các cột chứa dữ liệu lồng nhau
print(bookstores[["categories", "coordinates", "location"]].head(3))
                                          categories  \
0   [{'alias': 'bookstores', 'title': 'Bookstores'}]   
1  [{'alias': 'bookstores', 'title': 'Bookstores'...   
2   [{'alias': 'bookstores', 'title': 'Bookstores'}]     

                                         coordinates  \
0  {'latitude': 37.7975997924805, 'longitude': -1...   
1  {'latitude': 37.7885846793652, 'longitude': -1...   
2  {'latitude': 37.7589836120605, 'longitude': -1...    

                                            location  
0  {'address1': '261 Columbus Ave', 'address2': '...  
1  {'address1': '50 2nd St', 'address2': '', 'add...  
2  {'address1': '866 Valencia St', 'address2': ''...
Nạp dữ liệu gọn nhẹ với pandas

pandas.io.json

  • Tiểu mô-đun pandas.io.json có công cụ đọc/ghi JSON
    • Cần import riêng
  • json_normalize()
    • Nhận dict/danh sách dict (tương tự pd.DataFrame())
    • Trả về dataframe đã làm phẳng
    • Mẫu tên cột mặc định sau khi làm phẳng: attribute.nestedattribute
    • Đổi ký tự phân tách bằng tham số sep
Nạp dữ liệu gọn nhẹ với pandas

Nạp dữ liệu JSON lồng nhau

import pandas as pd
import requests

from pandas.io.json import json_normalize
# Thiết lập header, tham số và endpoint API api_url = "https://api.yelp.com/v3/businesses/search" headers = {"Authorization": "Bearer {}".format(api_key)} params = {"term": "bookstore", "location": "San Francisco"}
# Gọi API và trích xuất dữ liệu JSON response = requests.get(api_url, headers=headers, params=params) data = response.json()
Nạp dữ liệu gọn nhẹ với pandas
# Làm phẳng dữ liệu và nạp vào dataframe, dùng dấu gạch dưới
bookstores = json_normalize(data["businesses"], sep="_")
print(list(bookstores))
['alias', 
 'categories',
 'coordinates_latitude',
 'coordinates_longitude',
 ...
 'location_address1',
 'location_address2',
 'location_address3',
 'location_city',
 'location_country',
 'location_display_address',
 'location_state',
 'location_zip_code',
 ...
 'url']
Nạp dữ liệu gọn nhẹ với pandas

Dữ liệu lồng sâu

print(bookstores.categories.head())
0     [{'alias': 'bookstores', 'title': 'Bookstores'}]
1    [{'alias': 'bookstores', 'title': 'Bookstores'...
2     [{'alias': 'bookstores', 'title': 'Bookstores'}]
3     [{'alias': 'bookstores', 'title': 'Bookstores'}]
4    [{'alias': 'bookstores', 'title': 'Bookstores'...
Name: categories, dtype: object
Nạp dữ liệu gọn nhẹ với pandas

Dữ liệu lồng sâu

  • json_normalize()
    • record_path: chuỗi/danh sách chuỗi trỏ tới dữ liệu lồng nhau
    • meta: danh sách thuộc tính khác để nạp vào dataframe
    • meta_prefix: chuỗi tiền tố cho tên cột meta
Nạp dữ liệu gọn nhẹ với pandas

Dữ liệu lồng sâu

# Làm phẳng categories, kèm chi tiết doanh nghiệp
df = json_normalize(data["businesses"],
                    sep="_",

record_path="categories",
meta=["name", "alias", "rating", ["coordinates", "latitude"], ["coordinates", "longitude"]],
meta_prefix="biz_")
Nạp dữ liệu gọn nhẹ với pandas
print(df.head(4))
        alias               title                biz_name  \
0  bookstores          Bookstores   City Lights Bookstore   
1  bookstores          Bookstores  Alexander Book Company   
2  stationery  Cards & Stationery  Alexander Book Company   
3  bookstores          Bookstores       Borderlands Books   

                              biz_alias  biz_rating  biz_coordinates_latitude  \
0   city-lights-bookstore-san-francisco         4.5                 37.797600   
1  alexander-book-company-san-francisco         4.5                 37.788585   
2  alexander-book-company-san-francisco         4.5                 37.788585   
3       borderlands-books-san-francisco         5.0                 37.758984   

   biz_coordinates_longitude  
0                -122.406578  
1                -122.400631  
2                -122.400631  
3                -122.421638
Nạp dữ liệu gọn nhẹ với pandas

Ayo berlatih!

Nạp dữ liệu gọn nhẹ với pandas

Preparing Video For Download...