python - 无法以正确的格式将数据提取到 Pandas 数据框中

标签 python python-3.x pandas curl

我正在尝试从 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')))

电流输出 enter image description here

如何在每个标题下正确填充值。

预期格式 enter image description here

最佳答案

首先将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/

相关文章:

python - 将具有多个时区的 pandas 列转换为单个时区

python - 使用 pandas 和 ipywidgets 创建交互式绘图,使用数据帧列中的值作为输入

python - 在包含最长列表的 Pandas DF 中查找列的名称

python - Pytorch ValueError : Expected target size (2, 13),调用 CrossEntropyLoss 时得到 torch.Size([2])

Python 3 UnicodeDecodeError - 如何调试 UnicodeDecodeError?

python - 从 MainWindow 内的 QWidget 内的按钮更改 MainWindow 小部件

python - 在 QTabWidget 选项卡下创建一个 QMenubar

python - 相当于 numpy.roll 的 Pandas

python - 参数解析器错误 : too few arguments

python - 如果 TCP 客户端能够暂停服务器,当 TCP 服务器读取非阻塞套接字时