【问题标题】:Read JSON to pandas dataframe - ValueError: Mixing dicts with non-Series may lead to ambiguous ordering将 JSON 读取到 pandas 数据框 - ValueError:将 dicts 与非系列混合可能会导致排序不明确
【发布时间】:2018-09-05 10:45:55
【问题描述】:

我正在尝试将下面的 JSON 结构读入 pandas 数据帧,但它会抛出错误消息:

ValueError:将字典与非系列混合可能会导致模棱两可 订购。

Json 数据:

{
    "status": {
        "statuscode": 200,
        "statusmessage": "Everything OK"
    },

    "result": [{
        "id": 22,
        "club_id": 16182
    }, {
        "id": 23,
        "club_id": 16182
    }, {
        "id": 24,
        "club_id": 16182
    }, {
        "id": 25,
        "club_id": 16182
    }, {
        "id": 26,
        "club_id": 16182
    }, {
        "id": 27,
        "club_id": 16182
    }]
}

我怎样才能做到这一点?我试过下面的脚本...

j_df = pd.read_json('json_file.json')
j_df

with open(j_file) as jsonfile:
    data = json.load(jsonfile)

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

    如果您只需要数据框中的结果部分,那么这里的代码可以帮助您。

    import json
    import pandas as pd
    data = json.load(open('json_file.json'))
    
    df = pd.DataFrame(data["result"])
    

    【讨论】:

      【解决方案2】:

      您可以将json_normalizeassign 一起使用:

      from pandas.io.json import json_normalize
      import json
      
      with open('json_file.json') as data_file:    
          d= json.load(data_file)  
      
      df = json_normalize(d, 'result').assign(**d['status'])
      print (df)
         club_id  id  statuscode  statusmessage
      0    16182  22         200  Everything OK
      1    16182  23         200  Everything OK
      2    16182  24         200  Everything OK
      3    16182  25         200  Everything OK
      4    16182  26         200  Everything OK
      5    16182  27         200  Everything OK
      

      【讨论】:

        【解决方案3】:

        如果您只需要数据框中的结果部分,这里的代码可以帮助您:

        import json
        import pandas as pd
        data = json.load(open('json_file.json'))
        
        df = pd.DataFrame(data["result"])
        

        据我所知,发生 ValueError 是因为数据类型到处都是,一些字符串,一些列表,多个 {} 等。这个错误可以通过规范化数据来解决。为此,下面是代码:

        import json
        
        with open('json_file.json') as project_file:    
            data = json.load(project_file)  
        
        df = pd.json_normalize(data)
        

        【讨论】:

        • 模块 'pandas' 没有属性 'json_normalize'
        • 如果你得到上述错误“pandas”没有属性“json_normalize”,那么试试df=pd.json_normalize(data)。这是在 json 上调用 normalize 函数的新方法。
        猜你喜欢
        • 2021-02-19
        • 2021-01-05
        • 2021-08-20
        • 2019-11-22
        • 2021-12-25
        • 2019-07-11
        • 1970-01-01
        • 2017-12-29
        • 2015-12-14
        相关资源
        最近更新 更多