การนำเข้าข้อมูลด้วย pandas อย่างมีประสิทธิภาพ
Amany Mahfouz
Instructor



requests.get() สำหรับดึงข้อมูลจาก URL
requests.get(url_string) สำหรับดึงข้อมูลจาก URLparams: รับ dictionary ของพารามิเตอร์และค่าต่าง ๆ เพื่อปรับแต่งคำขอ APIheaders: รับ dictionary ใช้สำหรับยืนยันตัวตนกับ APIresponse ที่มีข้อมูลและ metadataresponse.json() จะคืนค่าเฉพาะข้อมูล JSONresponse.json() คืนค่าเป็น dictionaryread_json() รับค่าเป็น string เท่านั้น ไม่ใช่ dictionarypd.DataFrame()read_json() จะเกิดข้อผิดพลาด!





import requests import pandas as pdapi_url = "https://api.yelp.com/v3/businesses/search"# Set up parameter dictionary according to documentation params = {"term": "bookstore", "location": "San Francisco"}# Set up header dictionary w/ API key according to documentation headers = {"Authorization": "Bearer {}".format(api_key)}# Call the API response = requests.get(api_url, params=params, headers=headers)
# Isolate the JSON data from the response object
data = response.json()
print(data)
{'businesses': [{'id': '_rbF2ooLcMRA7Kh8neIr4g', 'alias': 'city-lights-bookstore-san-francisco', 'name': 'City Lights Bookstore', 'image_url': 'https://s3-media1.fl.yelpcdn.com/bphoto/VRydkkpVbA3CeVLBKzs2Vw/o.jpg', 'is_closed': False,
# Load businesses data to a dataframe
bookstores = pd.DataFrame(data["businesses"])
print(bookstores.head(2))
alias ... url
0 city-lights-bookstore-san-francisco ... https://www.yelp.com/biz/city-lights-bookstore...
1 alexander-book-company-san-francisco ... https://www.yelp.com/biz/alexander-book-compan...
[2 rows x 16 columns]
การนำเข้าข้อมูลด้วย pandas อย่างมีประสิทธิภาพ