【问题标题】:why i cant load json file to pandas data frame为什么我无法将 json 文件加载到 pandas 数据框
【发布时间】:2022-11-07 21:37:23
【问题描述】:

我的代码:

import json
import requests
responseGBP=requests.get("https://public.opendatasoft.com/api/records/1.0/search/?dataset=euro-exchange-rates&sort=date&facet=currency&rows=30&facet=date&q=date:[2020-12-01+TO+2020-12-31]&refine.currency=GBP")
response_jGBP=responseGBP.content.decode("utf-8")
df = pd.read_json(response_jGBP)
df

我收到此错误:

All arrays must be of the same length

我想获取货币数据,但无法将 json 文件转换为 pandas 数据框。 我收到“所有数组必须具有相同的长度”错误

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

    因为您没有正确分析字典结构。

    您必须了解,对于 pandas 行中的所有列,行数都相同,并且您还可以根据需要加载响应的特定部分。

    import pandas as pd
    res = requests.get("https://public.opendatasoft.com/api/records/1.0/search/?dataset=euro-exchange-rates&sort=date&facet=currency&rows=30&facet=date&q=date:[2020-12-01+TO+2020-12-31]&refine.currency=GBP")
    df = pd.DataFrame(res.json()["records"])
    

    上面的代码将加载数据,但不确定是否是你想要的,但你知道你必须查看第一个 JSON 结构。如果需要,您还必须对其进行修改以加载为数据框。

    【讨论】:

      【解决方案2】:

      lines=True 添加到您的d.read_json 函数中。

      import json
      import requests
      import pandas as pd
      
      responseGBP=requests.get("https://public.opendatasoft.com/api/records/1.0/search/?dataset=euro-exchange-rates&sort=date&facet=currency&rows=30&facet=date&q=date:[2020-12-01+TO+2020-12-31]&refine.currency=GBP")
      response_jGBP=responseGBP.content.decode("utf-8")
      df = pd.read_json(response_jGBP, lines=True)
      print(df)
      

      【讨论】:

        猜你喜欢
        • 2016-06-08
        • 2020-07-21
        • 2017-05-03
        • 2017-06-03
        • 2016-09-19
        • 1970-01-01
        • 2021-08-26
        • 1970-01-01
        • 2021-08-06
        相关资源
        最近更新 更多