【问题标题】:Is there a standard way to convert JSON to Dataframe? Or do different cases require different solutions?是否有将 JSON 转换为 Dataframe 的标准方法?还是不同的情况需要不同的解决方案?
【发布时间】:2022-08-14 05:27:03
【问题描述】:

我试图了解如何将包含 JSON 的 URL 转换为数据框。我正在测试这个示例代码:

import requests
r = requests.get(\'https://www.chsli.org/sites/default/files/transparency/111888924_GoodSamaritanHospitalMedicalCenter_standardcharges.json\')
print(r.json())

这给了我这个:

{\"name\":\"Good Samaritan Hospital Medical Center\",\"tax_id\":\"11-1888924\",\"code\":\"57320\",\"code type\":\"cpt\",\"code description\":\"Closure of abnormal drainage tract from bladder into vagina\",\"payer\":\"humana - medicare advantage\",\"patient_class\":\"O\",\"gross charge\":\"23452.80\",\"de-identified minimum negotiated charge\":\"769.90\",\"payer-specific negotiated charge\":\"3154.88\",\"de-identified maximum negotiated charge\":\"3154.88\",\"discounted cash price\":\"4690.56\"}
{\"name\":\"Good Samaritan Hospital Medical Center\",\"tax_id\":\"11-1888924\",\"code\":\"57320\",\"code type\":\"cpt\",\"code description\":\"Closure of abnormal drainage tract from bladder into vagina\",\"payer\":\"HEALTH FIRST\",\"patient_class\":\"O\",\"gross charge\":\"23452.80\",\"de-identified minimum negotiated charge\":\"769.90\",\"payer-specific negotiated charge\":\"769.90\",\"de-identified maximum negotiated charge\":\"3154.88\",\"discounted cash price\":\"4690.56\"}
: 421

现在,如果我尝试将所有内容都放入数据框中,就像这样......

df = pd.read_json(r.json(), orient=\'index\')
print(df.head())

我收到此错误:

NameError: name \'df\' is not defined

我认为可能有一种定制的方式来做到这一点,但我不确定。如何将此 JSON 转换为数据框?根据 JSON 结构的不同场景,是否有不同的方法来做到这一点?

  • 您编写的代码不会发生这种情况。你刚才在行上分配了df,它不能是未定义的。该错误消息与转换 JSON 无关,它是一个变量范围问题。
  • 我认为最后是 \': 421\' 。我认为这就是它被抛弃的原因。我不太了解 JSON,无法确定这里发生了什么。
  • 该 URL 不包含有效的 JSON。它是多个 JSON 对象,每个都在单独的行上,但它应该是 JSON 对象的数组。
  • 但是,如果读取 JSON 时出现问题,您应该会从 pd.read_json() 收到错误,而不是它后面的行。您是否在函数中读取 JSON,然后尝试在调用者中打印它?如果你在函数中没有global df,你会得到这个错误。

标签: python json python-3.x dataframe


【解决方案1】:

pandas.read_json 文档:https://pandas.pydata.org/docs/reference/api/pandas.read_json.html

任何有效的字符串路径都是可接受的。该字符串可以是一个 URL。有效的 URL 方案包括 http、ftp、s3 和文件。对于文件 URL,需要一个主机。本地文件可以是:file://localhost/path/to/table.json。

import pandas as pd

df = pd.read_json("http://raw.githubusercontent.com/BindiChen/machine-learning/master/data-analysis/027-pandas-convert-json/data/simple.json")
print(df)

【讨论】:

  • 这很简单,但我想也太简单了。当我在我发布的 URL 上运行该代码时,我得到了这个结果:loads(json,precision_float=self.precise_float), dtype=None ValueError: Trailing data
  • 我现在看到它是如何工作的!您需要在 .json 之后使用 ',lines=True'。这是完整的工作代码。将熊猫导入为 pd df = pd.read_json("chsli.org/sites/default/files/transparency/…", lines=True) print(df.head())
  • 哦,非常感谢分享那个 GuiEpi !!!
  • 荣幸! @灰
猜你喜欢
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
  • 2017-02-18
  • 1970-01-01
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多