【问题标题】:how to transform nested JSON object into rows and columns in Pandas如何将嵌套的 JSON 对象转换为 Pandas 中的行和列
【发布时间】:2021-08-29 13:37:06
【问题描述】:

我有一个 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)

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

【问题讨论】:

  • 你可以在这里添加你的文件,或者像你的文件这样的例子。也是预期输出的一个例子

标签: python json pandas dataframe nested


【解决方案1】:

丽图·帕蒂尔

您的 .jsonjson-dictionary(键、值):

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

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

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}

【讨论】:

  • 谢谢。但看起来它不像你在图片中显示的那样解析。代码是否完整?
  • @RituPatil - 已编辑 - 需要像这样分配给 conversationHistoryRecords:conversationHistoryRecords = data['conversationHistoryRecords']
  • 您关于 groupBy conversationId 的概念 - 并不简洁 - 因为整个 .json 只有 1 个 conversationId。
  • 感谢您的及时回复。会检查。我将进一步阅读此案。对于我的案子,你有什么具体的文件要阅读吗?
  • 精确 - 业务需求以及如何检查相关性和有价值的结论所需要的。
猜你喜欢
  • 1970-01-01
  • 2020-03-21
  • 2022-01-11
  • 2021-12-21
  • 2019-09-01
  • 1970-01-01
  • 2014-06-27
  • 2020-10-17
  • 1970-01-01
相关资源
最近更新 更多