Get MapQuest
unknown
python
3 years ago
2.5 kB
15
Indexable
''' đầu tiên sử dụng hàm Build_Request_From_MapQuest này
để tạo ra request để có thể get data từ MapQuest '''
def Build_Request_From_MapQuest(apiKey, x1, y1, x2, y2, filters):
'''
apiKey: truyền vào API
x1, y1, x2, y2:kiểu float, thông số của Bounding Box, chỉ định vùng tìm kiếm sự cố (incidents)
filters: optional, kiểu list, các loại sự cố cần tìm (incidents, construction, event, congestion).
Nếu rỗng thì mặc định = incidents,construction.
TrẢ về chuỗi string về URL để sử dụng trong get data.
'''
bbox = ",".join([str(x1), str(y1), str(x2), str(y2)])
request = "http://www.mapquestapi.com/traffic/v2/incidents?key="+str(apiKey)+"&boundingBox="+bbox+""
if filters != []:
f = ','.join(filters)
request = request + "&filters="+f
return request
'''
Get data bằng công thức lệnh
>>> !curl -X GET + URL
với URL = Build_Request_From_MapQuest(...)
Gán kết quả vào biến s.
Dòng 25 là ví dụ.
'''
s = !curl -X GET "http://www.mapquestapi.com/traffic/v2/incidents?key=AwpkydowEp2NQDncMwYzbFsoGk07HB8R&boundingBox=39.95,-105.25,39.52,-104.71&filters=construction,congestion,incidents"
'''
Sau khi có kết quả thô ở biến s,
truyền s vào hàm Json_To_DF để lấy Dataframe
'''
def Json_To_DF(s):
# s: data đã GET từ MapQuest ở dạng thô
# return df: trả về một DataFrame gồm các thuộc tính của từng incidents
mapquest_data = json.loads(s[0])
df = []
for i in range(len(mapquest_data['incidents'])):
incidents_key = list(mapquest_data['incidents'][i].keys())
incidents_key.remove('parameterizedDescription')
parameterized_key = mapquest_data['incidents'][i]['parameterizedDescription'].keys()
d = dict()
for key in incidents_key:
d.update({key:mapquest_data['incidents'][i][key]})
for key in parameterized_key:
d.update({key:mapquest_data['incidents'][i]['parameterizedDescription'][key]})
d.update({'URL': mapquest_data['mqUrl']})
d.update({'Copyright': mapquest_data['info']['copyright']['text']})
d.update({'CopyrightImage': mapquest_data['info']['copyright']['imageUrl']})
d.update({'Status': mapquest_data['info']['statuscode']})
d.update({'Message': mapquest_data['info']['messages']})
df.append(d)
return pd.DataFrame(df)
'''
Sau khi có kết quả thô ở biến s,
truyền s vào hàm Json_To_DF để lấy Dataframe
'''
df = Json_To_DF(s)
df.head()
'''
Get xong dữ liệu
'''Editor is loading...