首页 > 解决方案 > 如何将嵌套的 JSON 对象转换为 Pandas 中的行和列

问题描述

我有一个 json 文件,对 json 和 pandas 来说很新。如何根据对话 id 或 csv 数据展平此 JSON。

Json 数据在这里:https ://pastebin.pl/view/64022f08

import json
import pandas as pd
with open('/Users/rp/Downloads/apires.json') as f:
    data = json.load(f)
df1 = pd.json_normalize(data)
print(df1)

有人可以帮忙吗?这两天想不通。

标签: pythonjsonpandasdataframenested

解决方案


瑞图·帕蒂尔

您的.jsonjson-dictionary (key, value):

因此,要访问字典中的正确元素,您需要访问这样的元素:

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

dfMetadata = pd.DataFrame(data['_metadata'])
dfData =pd.DataFrame(data['conversationHistoryRecords'])

它将这个数据集从 .json 转换为两个数据帧。

在此处输入图像描述

为了获得您感兴趣的正确密钥:在此结构中,可以检查相关关系并研究此数据集。

还有一个选项可以访问此行中的特定行:

conversationHistoryRecords = data['conversationHistoryRecords']
campaign = conversationHistoryRecords[0]['campaign']

对于值得探索的数据,活动是可变的(在这种情况下):

{'campaignEngagementId': '2330596212',
 'campaignEngagementName': 'Engagement-123',
 'campaignId': '2266771712',
 'campaignName': 'Live_Chat_on_your_site',
 'goalId': '2266719412',
 'goalName': 'Interact with visitors',
 'engagementAgentNote': 'agent-note-test-messaging',
 'engagementSource': 'WEB_SITE',
 'visitorBehaviorId': '2379540212',
 'visitorBehaviorName': 'someVisitorBehavior',
 'engagementApplicationId': '28879660-84fd-4cd8-a1d7-ba3247bdb252',
 'engagementApplicationName': 'Some Mobile App Test',
 'engagementApplicationTypeId': '92274cfd-29e7-4d94-a013-0646212d8075',
 'engagementApplicationTypeName': 'Mobile App',
 'visitorProfileId': '2286779312',
 'visitorProfileName': 'All visitors',
 'lobId': 2389848512,
 'lobName': 'lob_123',
 'locationId': '2266779612',
 'locationName': 'Entire site',
 'profileSystemDefault': True,
 'behaviorSystemDefault': False}

推荐阅读