首页 > 解决方案 > 将带有列表和 dics 的 JSON 转换为数据框

问题描述

我想将 JSON 文件转换为易于搜索和定位有用信息的数据框。JSON 如下所示:

[
    {
        "testId": "test1",
        "testType": [
            {
                "value": "a",
                "startDate": "2019-01-01T08:00:00",
                "endDate": "2029-01-01T08:00:00"
            }
        ],
        "candidate": [
            {
                "value": {
                    "id": "b",
                    "name": "test"
                },
                "startDate": "2019-01-01T08:00:00",
                "endDate": "2029-01-01T08:00:00"
            }
        ],
        "testsite": [
            {
                "value": "c",
                "startDate": "2019-01-01T08:00:00",
                "endDate": "2029-01-01T08:00:00"
            }
        ]
    },
    {
        "testId": "test2",
        "testType": [
            {
                "value": "SG",
                "startDate": "2019-01-01T08:00:00",
                "endDate": "2029-01-01T08:00:00"
            }
        ],
        "maxcandidates": [
            {
                "value": {
                    "amount": "75"
                },
                "startDate": "2019-01-01T08:00:00",
                "endDate": "2029-01-01T08:00:00"
            }
        ],
        "candidate": [
            {
                "value": {
                    "id": "sei",
                    "name": "long island Limited"
                },
                "startDate": "2019-01-01T08:00:00",
                "endDate": "2029-01-01T08:00:00"
            }
        ],
        "mincandidates": [
            {
                "value": {
                    "amount": "5"
                },
                "startDate": "2018-04-01T08:00:00",
                "endDate": "2029-01-01T08:00:00"
            }
        ],
        "testSite": [
            {
                "value": "5227",
                "startDate": "2018-04-01T08:00:00",
                "endDate": "2029-01-01T08:00:00"
            }
        ]
    }
] 

它是 json 文件的一部分。这个 JSON 文件包含列表,一些属性包含字典。1 标准化这些数据的最有效方法是什么?2 如果我想在整个 JSON 文件中将“testType”转换为带有“testId”元数据的数据框,我该怎么做?

我将此命令用作

import json
import pandas as pd
from pandas.io.json import json_normalize

with open('test.json') as f:
    d=json.load(f)

type=json_normalize(data=d[:]['testType'], 
                            meta=['testId'])

它出现了 TypeError: list indices must be integers or slices, not str

或者如果我使用

import json
import pandas as pd
from pandas.io.json import json_normalize

with open('test.json') as f:
    d=json.load(f)

type=json_normalize(data=d[0]['testType'], 
                            meta=['testId'])

我可以将它转换为数据框,但它只能给我数组中的第一个元素而不是所有东西。

标签: pythonjsonpandasdataframe

解决方案


您可能可以执行以下操作:

pd.concat([json_normalize(data=e['testType'], meta=['testId']) for e in d])

value   startDate           endDate
0   a   2019-01-01T08:00:00 2029-01-01T08:00:00
0   SG  2019-01-01T08:00:00 2029-01-01T08:00:00

推荐阅读