【问题标题】:Could not get data from the NOAA API calls无法从 NOAA API 调用中获取数据
【发布时间】:2021-02-06 00:12:54
【问题描述】:

我正在尝试按照网站上提到的方法访问气象站数据:https://towardsdatascience.com/getting-weather-data-in-3-easy-steps-8dc10cc5c859 我正在为此使用 python。我还在学习python,我不知道为什么它会显示错误。我使用的代码行是:

r = requests.get('https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&datatypeid=\
                       TAVG&limit=1000&stationid=GHCND:USC00297461&startdate=2020-01-01&enddate=2020-10-22',
                       headers={'token':Token})
d = r.json()
avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']

错误是:

KeyError                                  Traceback (most recent call last)
<ipython-input-85-c1a56919f6ab> in <module>()
      4 d = r.json()
      5 #get the item (average temperature) from the response
----> 6 avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']

KeyError: 'results'

【问题讨论】:

    标签: python api noaa


    【解决方案1】:

    你得到一个错误,因为你应该有这个

    avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']
    

    而不是这个:

    avg_temps = [item for item in d['results'] if d['datatype']=='TAVG']
    

    区别是item['datatype'] 反而 d['datatype']

    【讨论】:

    • 这个解决方案对我不起作用。我正在使用您建议的那个(我尝试了两个只是为了确定)。它适用于较新的数据(例如 2020 年),但不适用于较旧的数据(1978 年)。对于较旧的数据,我仍然收到 OP 中提到的 keyerror。
    猜你喜欢
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2020-03-27
    • 2018-12-09
    相关资源
    最近更新 更多