【发布时间】:2021-07-04 11:54:50
【问题描述】:
我一直在使用 Python 和 Requests 模块按位置获取所有 Irelands Covid 数据。 我遇到了一个问题,我从 API 调用中获取数据的 dict 无法转换为 JSON,我想在 Pandas Dataframe 上显示它
现在,不幸的是,API 的网站有限,我必须为每个位置使用 for 循环来获取该区域的数据。然后当我这样做时,我将其推送到字典 thisdict["of that locations name"]
然后我尝试将它创建的所有 25 个字典转换为 JSON
toJSON = json.dumps(thisdict.values())
data = json.loads(toJSON)
现在这是我得到错误的地方 但是,如果我使用我创建的其中一个位置的位置,它将起作用,但我想要所有位置。这可能吗
toJSON = json.dumps(thisdict["Dublin"])
data = json.loads(toJSON)
我试过了
toJSON = json.dumps(*thisdict)
data = json.loads(toJSON)
与
toJSON = json.dumps(list(thisdict.values())
data = json.loads(toJSON)
所有代码都在这个链接中 https://replit.com/@MrGallen/GetC19ApiToCSVEveryCounty#main.py
# to handle data retrieval
import requests
# to manage json data
import json
# for pandas dataframes
import pandas as pd
counties = ["Carlow", "Cavan", "Clare", "Cork", "Donegal", "Dublin", "Galway", "Kerry", "Kildare", "Kilkenny", "Laois", "Leitrim", "Limerick", "Longford", "Louth", "Mayo", "Meath", "Monaghan", "Offaly", "Roscommon", "Sligo", "Tipperary", "Waterford", "Westmeath", "Wexford", "Wicklow"]
thisdict = {}
for county in counties:
url = "https://services1.arcgis.com/eNO7HHeQ3rUcBllm/arcgis/rest/services/Covid19CountyStatisticsHPSCIreland/FeatureServer/0/query?where=CountyName%20%3D%20'"+county+"'&outFields=CountyName,PopulationCensus16,TimeStamp,ConfirmedCovidCases,PopulationProportionCovidCases,ConfirmedCovidDeaths,ConfirmedCovidRecovered&returnGeometry=false&outSR=4326&f=json"
r = requests.get(url, stream=True)
#info = r.headers
#print(info)
r = r.json()
r = r["features"]
thisdict[county] = r
# decode json data into a dict object
toJSON = json.dumps(thisdict)
data = json.loads(toJSON)
# in this dataset, the data to extract is under 'features'
with open("sample.json", "w") as outfile:
json.dump(data, outfile)
df = pd.json_normalize(data)
print(df.head(10))
# Select a number of columns - all rows
CD = df[['attributes.CountyName', 'attributes.TimeStamp', 'attributes.ConfirmedCovidCases']]
print(CD) # DataFrame
【问题讨论】:
标签: python json pandas dictionary python-requests