Python TypeError:不可用类型:' dict'

时间:2017-10-02 12:52:38

标签: python-3.x api pandas data-science

我正在尝试使用API​​请求来收集天气数据,并最终使用pandas.to_csv将数据保存到CSV文件中。 API请求正在运行,但是当我尝试将API响应从字典转换为pandas时,我收到此错误。我非常感谢任何有关我做错的提示:

TypeError:不可用类型:' dict'

代码中的最后一行是乱搞的,shell返回错误:

from urllib.request import urlopen
import json
import pandas as pd

api_key = ""
date = "20170601"
zip_code = "53711"

response = urlopen("http://api.wunderground.com/api/%s/history_%s/q/%s.json"     % (api_key, date, zip_code))

json_data = response.read().decode('utf-8', 'replace')

data = json.loads(json_data)

for observation in data['history']['observations']:
     print("Date/Time:    " + observation['date']['pretty'])
     print("Temperature:  " + observation['tempi'])
     print("Humidity:     " + observation['hum'])

df = pd.DataFrame([data], columns=data.keys())

屏幕截图是shell输出中的数据: enter image description here

1 个答案:

答案 0 :(得分:1)

您可以将json_normalize与过滤列结合使用,也可以转换日期列to_datetime

from pandas.io.json import json_normalize

df = json_normalize(data['history']['observations'])

df = df[['date.pretty','tempi','hum']]
df['date.pretty'] = pd.to_datetime(df['date.pretty'])
print (df.head())
          date.pretty tempi hum
0 2017-06-01 00:15:00  49.8  83
1 2017-06-01 00:35:00  50.0  82
2 2017-06-01 00:55:00  49.1  85
3 2017-06-01 01:15:00  49.3  83
4 2017-06-01 01:35:00  48.2  85