python - 如何将嵌套的 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)
有人可以帮忙吗?这两天想不通。
解决方案
瑞图·帕蒂尔
您的.json是json-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}
推荐阅读
- python - python代码是否有可能知道它正在运行的vscode模式(调试或运行)?
- python - 使用二进制强制安装 python 包(熊猫)
- javascript - 代理对象被解析为 Promise 时的问题
- c++ - 在 C++ 中将结构数组保存到外部文件
- python - 是否有任何功能可以检测 xlsxwriter 中的行宽 = 0?
- typescript - 如何键入打字稿函数静态变量
- android - 为什么 DocumentFile.fromTreeUri 不创建与原始文件相同的 DocumentFile?
- java - Issue with logical operator for Strings
- python - Tensorflow-Keras 如何在不同机器上获得可重现的结果
- javascript - 无法在 react js 功能组件中使用变量,我正在使用 JSX 扩展文件