我正在尝试将英国警察免费 API 响应整理为可读格式 - csv 或 excel。 我正在使用请求库。我的初始代码以 json 格式获取响应:
import requests
r=requests.get('https://data.police.uk/api/crimes-street/all-crime?poly=51.169,-0.633:51.186,-0.5436:51.226,-0.6224&date=2019-12')
r_json=r.json()
for i in j:
for key,value in i.items():
print (key, ":", value)
上面的代码生成如下:
category : anti-social-behaviour location_type : Force location : {'latitude': '51.196818', 'street': {'id': 1147343, 'name': 'On or near Parking Area'}, 'longitude': '-0.605146'} context : outcome_status : None persistent_id : id : 79955592 location_subtype : month : 2019-12
如何为我得到的响应创建一个包含正确标题的表格?标题可以是“类别”、“纬度”、“街道”、“名称”、“经度”、“月份”。
最佳答案
您需要在字典树中获取北斗七星才能获取一些数据,例如纬度。结果被收集到列表集合中,然后加载到数据框中并保存为 csv 文件。
import requests
import pandas as pd
r=requests.get('https://data.police.uk/api/crimes-street/all-crime?poly=51.169,-0.633:51.186,-0.5436:51.226,-0.6224&date=2019-12')
r_json=r.json()
# collect data into list of lists
collected_data = []
for data in r_json:
category = data.get('category')
month = data.get('month')
latitude = ''
longitude = ''
street = ''
for key, value in data.items():
if key == 'location':
latitude = value.get('latitude')
longitude = value.get('longitude')
street = value.get('street').get('name')
collected_data.append([category, latitude, longitude, street, month])
# load data into data frame
df = pd.DataFrame(collected_data, columns = ['Category' , 'Latitude', 'Longitude', 'Street', 'Month'])
# save data frame into csv
df.to_csv('data.csv')
关于python - 使用 python 将 API 响应排序为 excel 或 csv。 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60015529/