Pandas字典中的扁平列表

2024-09-29 19:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下json数据


{
    "accountId": 999998,
    "actionTime": 1528381455013,
    "additionalInformation": {
        "eS": [
            {
                "labels": [
                    "R"
                ],
                "sc": 1.0,
                "title": "Company"
            },
            {
                    "labels": [
                        "Slurpee"
                    ],
                    "sc": 1.0,
                    "title": "Product"
                }
        ]
    },
    "apiStatus": "Removed fields because of resyndication policy",
    "archived": false,
    }

我想展平additionalInformation.eS的数据。我想在csv中的最后一列(通过dataframe.to_csv数据帧)是:

label, title, accountId, actionTime

["R"], Comapny, 999998, 1528381455013

["Slurpee"], Product, 999998, 1528381455013

我试过:


data_frame = json_normalize(data, record_path=["additionalInformation"], meta=[["eS", "label"]], errors='ignore')


data_frame = json_normalize(data, record_path=["additionalInformation", "eS"], meta=["label"], errors='ignore')

我已经为json的normalize函数引用了Stackoverflow answer和{a2}

所涵盖的大多数示例都将字典列表作为记录路径,我的示例将字典值作为列表。 请帮忙。 谢谢


Tags: csv数据jsondatalabelsestitleproduct
1条回答
网友
1楼 · 发布于 2024-09-29 19:21:16

我相信有一种不那么冗长的方法来完成这项工作,但这里有一个选择:

from pandas.io.json import json_normalize

data = {
    "accountId": 999998,
    "actionTime": 1528381455013,
    "additionalInformation": {
        "eS": [{
                "labels": [
                "R"
                ],
                "sc": 1.0,
                "title": "Company"
            },
            {
                "labels": [
                    "Slurpee", "other"
                ],
                "sc": 1.0,
                "title": "Product"
            }
        ]

    },
    "apiStatus": "Removed fields because of resyndication policy"
}

ac = data['accountId']
at = data['actionTime']
r = json_normalize(data['additionalInformation'], record_path = 'eS')

r['accountId'] = ac
r['actionTime'] = at

r = r.drop('sc', axis = 1)

r

给出:

enter image description here

相关问题 更多 >

    热门问题