我正在尝试从 API 中提取数据并将其写入 Pandas Dataframe 中,以便我可以进行一些转换。
import requests
headers = {
'Authorization': 'Api-Key',
}
params = (
('locodes', 'PLWRO,DEHAM'),
)
response = requests.get('https://api.xxx.com/weather/v1/forecasts', headers=headers, params=params)
API调用的结果
response.text
'{"results":[{"place":{"type":"locode","value":"PLWRO"},"measures":[{"ts":1571896800000,"t2m":10.72,"t_min":10.53,"t_max":11.99,"wspd":8,"dir":"SE","wgust":12,"rh2m":87,"prsmsl":1012,"skcover":"clear","precip":0.0,"snowd":0,"thunderstorm":"N","fog":"H"}]},{"place":{"type":"locode","value":"DEHAM"},"measures":[{"ts":1571896800000,"t2m":10.79,"t_min":10.3,"t_max":10.9,"wspd":13,"dir":"ESE","wgust":31,"rh2m":97,"prsmsl":1008,"skcover":"partly_cloudy","precip":0.0,"snowd":0,"thunderstorm":"N","fog":"H"}]}]}'
当尝试进入 pandas 数据帧时,它的格式不正确。
import pandas as pd
import io
urlData = response.content
rawData = pd.read_csv(io.StringIO(urlData.decode('utf-8')))
如何在每个标题下正确填充值。
最佳答案
首先将json转换为字典,然后需要进行一些处理,将locode
添加到measures
,合并字典,将它们附加到列表中,最后调用DataFrame
构造函数:
import json
d = json.loads(response.text)
out = []
for x in d['results']:
t = x['place']['type']
v = x['place']['value']
for y in x['measures']:
y = {**{t:v}, **y}
out.append(y)
#print (out)
df = pd.DataFrame(out)
print (df)
locode ts t2m t_min t_max wspd dir wgust rh2m prsmsl \
0 PLWRO 1571896800000 10.72 10.53 11.99 8 SE 12 87 1012
1 DEHAM 1571896800000 10.79 10.30 10.90 13 ESE 31 97 1008
skcover precip snowd thunderstorm fog
0 clear 0.0 0 N H
1 partly_cloudy 0.0 0 N H
关于python - 无法以正确的格式将数据提取到 Pandas 数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58534350/