【问题标题】:Pandas read json ValueError: Protocol not known熊猫读取 json ValueError:协议未知
【发布时间】:2022-05-10 19:14:51
【问题描述】:

我不久前运行了这些代码,它可以工作,但现在有一个 ValueError:协议未知。谁能帮忙。谢谢。

import json
temp = json.dumps([status._json for status in tweet]) #create JSON
newdf = pd.read_json(temp, orient='records')

【问题讨论】:

  • 你能分享你的 json temp 吗?
  • @Psidom:它只是 tweepy 创建的推文的 json。只有当我在环境中运行代码时才会出现错误。如果我在基地运行它,没有错误。无论如何,这是完整的错误通知:ValueError: Protocol not known: [{"created_at": "Mon Aug 24 03:00:06 +0000 2020", "id": 1297730373137453056, "id_str": "1297730373137453056", "full_text": "Dietary and Physical Activity Behaviors Among High School Students \u2014 Youth Risk Behavior Survey, United State... https
  • 如果我在base中运行它,没有错误。那么它可能不是pandas的问题。
  • @psidom:谢谢。我很新。您能否建议在这种情况下在环境中安装哪些软件包?
  • 如果不了解您的环境的详细信息,我认为我无法提出建议。你需要先弄清楚是哪一行导致了问题。

标签: python pandas


【解决方案1】:

我的解决方案是使用StringIO,如下所示:

from io import StringIO
newdf = pd.read_json(StringIO(temp))

看起来 Pandas 1.1 中的 pd.read_json 不再接受简单字符串。

【讨论】:

  • 刚刚在这里测试过,效果很好,谢谢!
  • StringIO 对使它工作的 json 做了什么?
  • 看起来 read_json 现在寻找一个类似文件的对象而不是一个类似字符串的对象。 StringIO 为字符串提供了一个类似文件的接口。来自 pandas 文档:通过类文件对象,我们指的是具有 read() 方法的对象,例如文件处理程序(例如通过内置的 open 函数)或 StringIO。
  • 问题可能是数据包含某种形式的路径或 URL。就我而言,在数据开始包含 URL 之前,我不必使用 StringIO()。我希望更容易找到有关此的文档。
【解决方案2】:

据我所知,这个问题是由熊猫更新引起的。 1.1.0 更新对 read_json 函数进行了一些更改。

将 pandas 版本设置为 1.0.5 时,我可以让我的代码正常工作

https://pandas.pydata.org/docs/whatsnew/v1.1.0.html

【讨论】:

  • 将版本设置为 1.0.5 对我有用。我也尝试了较新的 1.1.1 版本,但这个没有。
【解决方案3】:

我同意 ehabets

from io import StringIO
df = pd.read_json(StringIO(json_demo))

现在,pd.read_json 需要文件类型的 json。这意味着 pd.read_json("xxx.json") 可以工作。

【讨论】:

    【解决方案4】:

    你的代码:

    import json
    temp = json.dumps([status._json for status in tweet]) #create JSON
    newdf = pd.read_json(temp, orient='records')
    

    修复代码:

    import json
    from io import StringIO
    temp = StringIO(json.dumps([status._json for status in tweet])) #create JSON
    df = pd.read_json(StringIO(temp, orient='records')
    

    它适用于 pandas==1.1.3

    【讨论】:

      【解决方案5】:

      供参考,如果上述失败的另一种方法:

      通过 Microsoft Excel 将现有 Excel 文件转换为 .XLSX 格式并保存

      【讨论】:

      猜你喜欢
      • 2017-06-14
      • 2018-03-04
      • 2019-03-31
      • 2017-03-28
      • 2018-01-14
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多