目前,我正在尝试从包含日期和国家/地区的json文件中获取“严格性”数据。这是json输出的摘录:
import pandas as pd
import json
from bs4 import BeautifulSoup
# load file
with open("Stringency April 8.txt") as file:
stringency_data = json.load(file)
stringency_data["data"]
#this gives the output:
{'2020-01-02': {'ABW': {'confirmed': None,`
'country_code': 'ABW',
'date_value': '2020-01-02',
'deaths': None,
'stringency': 0,
'stringency_actual': 0},
'AFG': {'confirmed': 0,
'country_code': 'AFG',
'date_value': '2020-01-02',
'deaths': 0,
'stringency': 0,
'stringency_actual': 0},
'AGO': {'confirmed': None,
'country_code': 'AGO',
'date_value': '2020-01-02',
'deaths': None,
'stringency': 0,
'stringency_actual': 0},
'AUS': {'confirmed': 0,
'country_code': 'AUS',
'date_value': '2020-01-02',
'deaths': 0,
'stringency': 7.14,
'stringency_actual': 7.14},
'AUT': {'confirmed': 0,
'country_code': 'AUT',
'date_value': '2020-01-02',
'deaths': 0,
'stringency': 0,
'stringency_actual': 0},.........
到目前为止,这是我的代码(为方便起见,我将其缩短了一点):
# create empty list for dates
date_index = []
[date_index.append(date) for date in stringency_data["data"]]
#creates empty lists for countries
Australia = []
Austria = []
...
US = []
# put these lists into a list
countries_lists = [Australia, Austria,...US]
# put country codes into a list
country_codes = ["AUS", "AUT",..."USA"]
# loop through countries
i = 0
for country, code in zip(countries_lists, country_codes):
while i<=len(date_index):
country.append(stringency_data["data"][date_index[i]][code]["stringency_actual"])
i+=1
当我打印列表“ Australia”时,我会得到所有想要的值。但是从奥地利开始的任何国家仍然是一个空白清单。
我得到输出-KeyError:“ AUS”。这表明该代码检索了整个时间序列,但仅针对第一个国家(澳大利亚)。如何为每个国家代码循环?
As also seen in the comments, it seems like you don't have the
AUS
key in one (or multiple) timeframe(s).基本上,您尝试在不包含该国家/地区的年/月(日期段)中检索AUS的数据。当您尝试在某个国家/地区不受大流行影响的时间范围内访问某个国家/地区的数据时,这会导致它们出现关键错误。
您的列表包含所有国家代码:
尽管某些日期输入未包含所有国家/地区。
解决方法?为这些情况分配默认的“值”或任何适合您的值。
The question/answers from this post might be helpful.