Python 将 JSON 读取到 Pandas 数据帧 - ValueError:将 dicts 与非系列混合可能会导致排序不明确

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49505872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:06:44  来源:igfitidea点击:

Read JSON to pandas dataframe - ValueError: Mixing dicts with non-Series may lead to ambiguous ordering

pythonjsonpandas

提问by userPyGeo

I am trying to read in the JSON structure below into pandas dataframe, but it throws out the error message:

我试图将下面的 JSON 结构读入 Pandas 数据帧,但它抛出了错误消息:

ValueError: Mixing dicts with non-Series may lead to ambiguous ordering.

ValueError:将 dicts 与非系列混合可能会导致排序不明确。

Json data:

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
    }]
}

How do I get this right? I have tried the script below...

我该如何做对?我试过下面的脚本...

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

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

回答by Rao Sahab

If you just need the result part in a dataframe, then here is the code to help you.

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

import json
import pandas as pd
data = json.load(open('json_file.json'))

df = pd.DataFrame(data["result"])

回答by jezrael

You can use json_normalizewith assign:

你可以用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