【问题标题】:Json_normalise from nested API to DF throwing type errorJson_normalise 从嵌套 API 到 DF 抛出类型错误
【发布时间】:2021-06-27 21:15:00
【问题描述】:

我正在尝试使用具有以下结构的 api,并将其加载到 pandas DF 中,每个项目 ID 有一行,例如2、6 以及每个条目的 high、hightime、low 和 lowtime 列。

{
"data": {
    "2": {
        "high": 142,
        "highTime": 1617214328,
        "low": 140,
        "lowTime": 1617214323
    },
    "6": {
        "high": 182198,
        "highTime": 1617214063,
        "low": 182198,
        "lowTime": 1617214137

到目前为止,我一直在 json 响应上使用 json_normalise,它为每个条目加载一行,其中包含多个嵌套列:

data.2.high | data.2.highTime | data.2.low | data.2.lowTime etc

作为我的结果,我尝试为“数据”添加记录路径,这样可以解决它是一个嵌套列表的事实,但这样做会引发

 raise TypeError(
257                     f"{js} has non list value {result} for path {spec}. "
258                     "Must be list or null."

我认为这是因为我的 res['data'] 类型是一个字典,而不是它本身的列表,但我有点困惑如何解决这个问题,或者这是否正确。

任何帮助将不胜感激

【问题讨论】:

  • 代码df = pd.DataFrame.from_records(json_data['data']).T 有效吗?
  • 是的!这完美无缺。你能向我解释为什么这是正确的方法而不是 json_normalise 或其他方式吗?谢谢:)
  • 我在下面解释了,如果清楚请告诉我=)

标签: python json pandas json-normalize


【解决方案1】:

TL;DR

随便用

df = pd.DataFrame.from_records(json_data['data']).T.reset_index()

说明

在您的场景中,pandas from_recordsjson_normalise 效果更好。之所以会出现这种情况,是因为您的响应的结构是 id 是键而不是值。

例如,对于这个响应示例,其中有一个键 id 及其对应的值

json_data={
"data": [{
        "id":2,
        "high": 142,
        "highTime": 1617214328,
        "low": 140,
        "lowTime": 1617214323
    },{
        "id":6,
        "high": 182198,
        "highTime": 1617214063,
        "low": 182198,
        "lowTime": 1617214137
    }]}

可以正常使用json_normalize,如下所示。

pd.json_normalize(json_data['data'])
id  high    highTime    low     lowTime
2   142     1617214328  140     1617214323
6   182198  1617214063  182198  1617214137

但是,您的 JSON 响应包含 id 作为键,

json_data={
"data": {
    "2": {
        "high": 142,
        "highTime": 1617214328,
        "low": 140,
        "lowTime": 1617214323
    },
    "6": {
        "high": 182198,
        "highTime": 1617214063,
        "low": 182198,
        "lowTime": 1617214137
    }}}

所以from_records 效果更好。

df = pd.DataFrame.from_records(json_data['data']).T.reset_index()
index   high    highTime    low     lowTime
2       142     1617214328  140     1617214323
6       182198  1617214063  182198  1617214137

此外,由于您可能传递了完整的 json 响应 json_data,而不是通过数据键 json_data['data'] 进行选择,因此事情无法正常工作。

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 2021-04-24
    • 2019-05-20
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2021-10-31
    相关资源
    最近更新 更多