【问题标题】:TypeError: list indices must be integers or slices, not str while retrieving data from APITypeError:从 API 检索数据时,列表索引必须是整数或切片,而不是 str
【发布时间】:2019-09-17 02:26:50
【问题描述】:

尝试使用机器学习算法通过 openweathermap 批量历史 API 预测天气。我一直使用https://stackabuse.com/using-machine-learning-to-predict-the-weather-part-1/ 作为我完成此任务的主要资源。但是,它一直给我一个标题中专门针对第 27 行列出的类型错误: 温度 = 数据['main']['temp'],

from datetime import datetime
from datetime import timedelta
import time
from collections import namedtuple
import pandas as pd
import requests
import matplotlib.pyplot as plt

#Data collection and Organization
url = 'http://history.openweathermap.org//storage/d12a3df743e650ba4035d2c6d42fb68f.json'

target_date = datetime(2018, 4, 22)
features = ["date", "temperature", "pressure", "humidity", "maxtemperature", "mintemperature"]
DailySummary = namedtuple("DailySummary", features)


def extract_weather_data(url, target_date, days):
    records = []
    for _ in range(days):
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
            records.append(DailySummary(
                date = target_date,
                temperature = data['main']['temp'],
                pressure = data['main']['pressure'],
                humidity = data['main']['humidity'],
                maxtemperature = data['main']['temp_max'],
                mintemperature = data['main']['temp_min']))
            time.sleep(6)
            target_date += timedelta(days =1)
    return records

records = extract_weather_data(url, target_date, 365)
#Finished data collection now begin to clean and process data using Pandas
df = pd.DataFrame(records, columns=features).set_index('date')
tmp = df[['temperature','pressure','humidty', 'maxtemperature', 'mintemperature']].head(10)

def derive_nth_day_feature(df, feature, N):
        rows = df.shape[0]
        nth_prior_measurements = [None]*N + [df[feature][i-N] for i in range(N, rows)]
        col_name = "{}_{}".format(feature, N)
        df[col_name]= nth_prior_measurements
for feature in features:
    if feature != 'date':
        for N in range (1, 4):
            derive_nth_day_feature(df, feature, N)

df.columns

【问题讨论】:

  • 粘贴你得到的异常。这将有助于以更好的方式帮助您。首先,不要将, 放在末尾,否则您将不必要地创建元组。而且,我猜这可能是原因之一。
  • JSON 本质上是列表和字典。当您尝试使用关键字访问时,这意味着它应该是字典。但是,您尝试访问的是一个需要列表索引的列表。执行print(data),然后找出您尝试作为关键字main 访问的最外层是什么。如果main存在,进一层看看是列表还是字典等。

标签: python python-3.x tensorflow machine-learning openweathermap


【解决方案1】:

您得到的响应是一个字典列表。所以你应该迭代列表,然后从每个项目中获取温度

response = requests.get(url)
data = response.json()
for d in data:
    print(d['main']['temp'])

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2020-05-14
    相关资源
    最近更新 更多